OSDN Git Service

get rid of Text::Ngram(not in Fedora repo)
[rec10/rec10-git.git] / rectool / trunk / rectool.pl
1 #!/usr/bin/perl
2 # -d:SmallProf
3 #use Perl6::Slurp;
4 #use XML::Simple;
5 #use CGI;
6 #use CGI::Lite;
7 #use Date::Manip;
8 #Date_Init("TZ=JST","ConvTZ=JST");
9 #use SVG;
10 #use KCatch;
11 use warnings;
12 use Algorithm::Diff qw(LCS);
13 use Archive::Zip;
14 use CGI;
15 use CGI::Carp qw( fatalsToBrowser warningsToBrowser );
16 use Config::Simple;
17 use Data::Dumper;
18 use Date::Simple;
19 use DateTime;
20 use DBI;
21 use MIME::Base64;
22 use File::Slurp;
23 use Sort::Naturally;
24 use Time::Piece;
25 use Time::Seconds;
26 use Time::HiRes;
27 use Tie::IxHash;
28 #require SVG Time::Simple XML::Atom Encode List::Compare List::Util
29 use utf8;
30 #%DB::packages = ( 'main' => 1 );
31
32
33 ################ バージョン定義 ################
34
35
36 my $rectool_version = 101;
37
38
39 ################ 初期化ここから ################
40
41
42 my $tz = DateTime::TimeZone->new( name => 'local' );
43 my $hires = Time::HiRes::time();
44
45 my $cfg = new Config::Simple;
46 if ( -e 'rec10.conf' ) {
47         $cfg->read( 'rec10.conf' );
48 }
49 elsif ( -e '/etc/rec10.conf' ) {
50         $cfg->read( '/etc/rec10.conf' );
51 }
52 else { 
53         die 'rec10.confが見つかりません。';
54 }
55
56 my $sql = $cfg->param( 'db.db' );
57
58 if ( $sql eq 'MySQL' ) {
59         my $name = $cfg->param( 'db.mysql_dbname' );
60         my $host = $cfg->param( 'db.mysql_host' );
61         my $port = $cfg->param( 'db.mysql_port' );
62         my $user = $cfg->param( 'db.mysql_user' );
63         my $pass = $cfg->param( 'db.mysql_passwd' );
64         $dbh = DBI->connect("dbi:mysql:$name:$host:$port", $user, $pass, {
65                 AutoCommit => 1,
66                 RaiseError => 1,
67                 mysql_enable_utf8 => 1, # only availavle for MySQL
68         });
69         $dbh->do( 'SET NAMES utf8' );
70 }
71
72 my $rec10_version = eval {
73         $dbh->selectrow_array( "SELECT version FROM in_status " );
74 };
75
76 my $HTML;
77
78 $HTTP_HEADER = "Content-Type: text/html\n\n";
79 $HTML .= <<EOM;
80 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
81 <html lang="ja">
82 <head>
83 <title>Rec10%HTML_TITLE_OPT%</title>
84 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
85 <meta http-equiv="Content-Script-Type" content="text/javascript">
86 <meta http-equiv="Content-Style-Type" content="text/css">
87 <meta name="robots" content="noindex,nofollow,noarchive">
88 <link rev="made" href="Rea10">
89 <link rel="alternate" type="application/atom+xml" title= "Rec10 Atom Feed" href="./rectool.pl?mode=atom">
90 %REFRESH%
91 %SCRIPT%
92 %CSS%
93 </head>
94 <body>
95 %HTML_HEADER%
96 EOM
97
98 my ( $user, $pass, $auth );
99 ( $user, $pass ) = eval {
100         $dbh->selectrow_array( "SELECT webuser, webpass FROM in_settings " );
101 };
102
103 if ( $user and $pass ) {
104         if ( $ENV{'HTTP_AUTHORIZATION'} ) {
105                 my ( $base64 ) = $ENV{'HTTP_AUTHORIZATION'} =~ /Basic\s(.*)/;
106                 if ( $base64 eq encode_base64( "$user:$pass" ) ) {
107                         $auth = 1;
108                 }
109                 else {
110                         $auth = 0;
111                 }
112         }
113         else {
114                 $auth = 0;
115         }
116 }
117 else {
118         $auth = 1;
119 }
120
121 if ( !$auth ) {
122         my ( $base64 ) = $ENV{'REMOTE_USER'} =~ /Basic (.*)/;
123         $HTTP_HEADER = qq {Status: 401 Authorization Required\nWWW-Authenticate: Basic realm="Protected Rec10 $ENV{'HTTP_AUTHORIZATION'}"\n} . $HTTP_HEADER;
124         goto end;
125 }
126
127 if ( $rec10_version != $rectool_version ) {
128         $HTML .= qq {<div style="font-size: 200%; font-weight: bold; color: red">\n};
129
130         if ( $rec10_version > $rectool_version ) {
131                 $HTML .= qq {Rec10本体のバージョンが新しいため、実行できません。<br>\n};
132                 $HTML .= qq {rectoolのバージョンアップを行ってください。<br>\n};
133         }
134
135         if ( $rec10_version < $rectool_version ) {
136                 $HTML .= qq {Rec10本体のバージョンが古いため、実行できません。<br>\n};
137                 $HTML .= qq {Rec10のバージョンアップを行ってください。<br>\n};
138         }
139
140         $HTML .= qq {Rec10のバージョンは$rec10_version 、rectoolのバージョンは$rectool_version です。<br>\n};
141         $HTML .= qq {<a href="http://sourceforge.jp/projects/rec10/">公式ページ</a>\n};
142         goto end;
143 }
144
145 $q = new CGI;
146 %params = $q->Vars;
147 $mode = $params{ 'mode' };
148 $mode_sub = $params{ 'mode_sub' };
149
150 ################ %chtxt_chnameの準備 ################
151
152 my %chtxt_chname;
153 my %chtxt_0_chname;
154 tie %chtxt_0_chname, 'Tie::IxHash';
155
156 my $ary_ref = $dbh->selectall_arrayref(
157         "SELECT chtxt, chname, ch, bctype FROM epg_ch
158         WHERE visible = 1"
159 );
160
161 %chtxt_chname = map { $_->[0], $_->[1] } @{$ary_ref};
162
163 # NHK BS 1/2/hiをBS/CSから除外(101-103) - by 2011/04
164 # te: 地上波、BSのNHK以外
165 # bc: BSのNHK、CS
166 my @te_ary = grep $_->[0]=~ /^\d|BS_(?!(10|19)[1-3])/, @{$ary_ref};
167 my @bc_ary = grep $_->[0]!~ /^\d|BS_(?!(10|19)[1-3])/, @{$ary_ref};
168
169 # teの操作(まとめる)
170 foreach my $line ( @te_ary ) {
171         # te xx_yyyy(chtxt) -> xx(ch)
172         if ( $line->[3] =~ /te/ ) {
173                 push @{ $chtxt_0_chname{        $line->[2] . '_0'} }, $line->[1];
174         }
175         else {
176                 push @{ $chtxt_0_chname{'BS_' . $line->[2]       } }, $line->[1];
177         }
178 }
179 foreach my $key ( keys %chtxt_0_chname ) {
180         my @chname = @{ $chtxt_0_chname{$key} };
181         if ( @chname >= 2 ) {
182                 # 2つ以上ある場合
183                 my @tmp = map { my @ary = split //, $_; \@ary } @chname;
184                 # 1つ目と2つ目のみ比較
185                 # FIXME: すべてを比較するべき
186                 $chtxt_0_chname{$key} = join '', LCS( $tmp[0], $tmp[1] );
187         }
188         else {
189                 # 1つしかない場合
190                 $chtxt_0_chname{$key} = $chname[0];
191         }
192 }
193
194 # bs/csの操作(そのまま)
195 foreach my $line ( @bc_ary ) {
196         $chtxt_0_chname{$line->[0]} = $line->[1];
197 }
198 undef $ary_ref;
199
200
201 ################ 定数宣言 ################
202
203
204 tie %type, 'Tie::IxHash';
205 %type = (
206         'search_everyday'          => '隔日検索',
207         'search_today'             => '当日検索',
208         'reserve_flexible'         => '浮動予約',
209         'reserve_fixed'            => '確定予約',
210
211         'reserve_running'          => '録画途中',
212
213         'convert_b25_ts'           => '解読予約',
214         'convert_b25_ts_running'   => '解読途中',
215         'convert_b25_ts_miss'      => '解読失敗',
216
217         'convert_ts_mp4'           => '縁故予約',
218         'convert_ts_mp4_running'   => '縁故於鯖',
219         'convert_ts_mp4_network'   => '縁故於網',
220         'convert_ts_mp4_finished'  => '縁故完了',
221
222         'convert_avi_mkv'          => '変換旧露',
223         'convert_avi_mp4'          => '変換旧四',
224         'convert_mkv_mp4'          => '変換露四',
225         'convert_mkv_mp4_runnings' => '換途露四',
226
227         'auto_suggest_dec'         => '予測解読',
228         'auto_suggest_enc'         => '予測縁故',
229         'auto_suggest_avi2fp'      => '予測旧四',
230         'auto_suggest_ap2fp'       => '予測露四',
231
232         'move_end'                 => '移動完了',
233 );
234
235 %type_suggest = (
236         'auto_suggest_dec'    => 'convert_b25_ts',
237         'auto_suggest_enc'    => 'convert_ts_mp4',
238         'auto_suggest_avi2fp' => 'convert_avi_mkv',
239         'auto_suggest_ap2fp'  => 'convert_mp4_mkv',
240 );
241
242 %color = (
243         'search_everyday'        => '#8B008B',
244         'search_today'           => '#8B008B',
245         'reserve_flexible'       => '#4169E1',
246         'reserve_fixed'          => '#4169E1',
247         'reserve_running'        => '#FF8C00',
248         'convert_b25_ts'         => '#CD5C5C',
249         'convert_b25_ts_running' => '#DC143C',
250         'convert_ts_mp4'         => '#32CD32',
251         'convert_ts_mp4_running' => '#2E8B57',
252         'convert_ts_mp4_network' => '#808000',
253
254         'other'                  => '#A0A0A0',
255 );
256
257 $type_user_made = "( 'search_everyday', 'search_today', 'reserve_flexible', 'reserve_fixed', 'reserve_running' )";
258
259 tie %category, 'Tie::IxHash';
260 %category = (
261         'news'        => { name => 'ニュース・報道'          , color => '#ff0000' }, 
262         'sports'      => { name => 'スポーツ'                , color => '#ff8000' }, 
263         'information' => { name => '情報'                    , color => '#ffff00' }, 
264         'drama'       => { name => 'ドラマ'                  , color => '#80ff00' }, 
265         'music'       => { name => '音楽'                    , color => '#00ff00' }, 
266         'variety'     => { name => 'バラエティ'              , color => '#00ff80' }, 
267         'cinema'      => { name => '映画'                    , color => '#00ffff' }, 
268         'anime'       => { name => 'アニメ・特撮'            , color => '#0080ff' }, 
269         'documentary' => { name => 'ドキュメンタリー・教養'  , color => '#0000ff' }, 
270         'stage'       => { name => '演劇'                    , color => '#8000ff' }, 
271         'hobby'       => { name => '趣味・実用'              , color => '#ff00ff' }, 
272         'etc'         => { name => 'その他'                  , color => '#ff0080' }, 
273 );
274
275 ################ 初期化ここまで ################
276
277
278 ################ mode=schedule ################
279
280 if ( $mode eq 'schedule' ) {
281
282         $HTML =~ s/%HTML_TITLE_OPT%/ - Schedule Viewer/;
283         #$HTML =~ s|%REFRESH%|<meta http-equiv="refresh" content="300">|;
284         $css = <<EOM;
285                 <style type="text/css">
286                 td {
287                         white-space: nowrap;
288                 }
289                 </style>
290 EOM
291         $css =~ s/^\t{2}//gm;
292         $HTML =~ s/%CSS%/$css/;
293
294         my $order = $params{ 'order' };
295         my $extra = $params{ 'extra' };
296         if ( $order ne 'id' ) {
297                 $order = 'btime';
298         }
299         $reverse_extra = $extra            ? '' : '&amp;extra=1';
300         $forward_order = $order eq 'btime' ? '' : '&amp;order=id';
301
302         my $ary_ref = $dbh->selectall_arrayref(
303                 "SELECT id, type, timeline.chtxt, epg_ch.chname, title, btime, etime, opt, deltaday, deltatime, 
304                 epgtitle, epgbtime, epgetime, epgexp, epgduplicate, epgchange, counter 
305                 FROM timeline 
306                 LEFT OUTER JOIN epg_ch ON timeline.chtxt = epg_ch.chtxt 
307                 ORDER BY $order"
308                 , {Slice=>{}});
309
310         $HTML .= qq {<div style="font-size: 80%; float: left">\n};
311         $HTML .= qq {<form method="get" action="rectool.pl">\n};
312         $HTML .= qq {<div>\n};
313         $HTML .= qq {<input type="hidden" name="mode" value="change">\n};
314         $HTML .= qq {<table summary="rectimetable" border=1 cellspacing=0>\n<tr>\n};
315         $HTML .= qq {<th><a href="rectool.pl?mode=schedule$forward_order$reverse_extra">■</a></th>\n};
316         $HTML .= qq {<th><a href="rectool.pl?mode=schedule&amp;order=id">ID</a></th>\n};
317         $HTML .= qq {<th>タイプ</th>\n};
318         $HTML .= qq {<th>チャンネル</th>\n};
319         $HTML .= qq {<th>タイトル</th>\n};
320         $HTML .= qq {<th><a href="rectool.pl?mode=schedule">開始時刻</a></th>\n};
321         $HTML .= qq {<th>終了時刻</th>\n};
322         $HTML .= qq {<th>録画時間</th>\n};
323         $HTML .= qq {<th>オプション</th>\n};
324         $HTML .= qq {<th>dd</th>\n};
325         $HTML .= qq {<th>dt</th>\n};
326         $HTML .= qq {<th>残り</th>\n};
327         $HTML .= qq {</tr>\n};
328         foreach my $line ( @{ $ary_ref } ) {
329
330                 $type = $type{$line->{type}} || $line->{type};
331                 if    ( $line->{type} =~ /^search/ ) {
332                         $type = qq {<span style="color: #8B008B">$type</span>};
333                         $line->{deltaday} = qq {<span style="color: #FF0000">空</span>} if ( !$line->{deltaday} && $line->{type} eq 'search_everyday' );
334                         $line->{deltatime} = qq {<span style="color: #FF0000">空</span>} if ( !$line->{deltatime} );
335                 }
336                 else {
337                         my $color = $color{$line->{type}} ? $color{$line->{type}} : $color{'other'};
338                         $type = qq {<span style="color: $color">$type</span>};
339                 }
340                 # 地上波の場合、xx_yyyをxx_0に置換する
341                 ( $line->{chtxt_0} = $line->{chtxt} ) =~ s/(\d+)_/$1_0/;
342                 # chnameが無いとき(移動縁故など)、chtxtを代わりに使う
343                 $line->{chname} = 
344                         $line->{chname} || 
345                         $chtxt_0_chname{$line->{chtxt}} || 
346                         $chtxt_0_chname{$line->{chtxt_0}};
347                 if ( !$line->{chname} ) {
348                         # chnameが無いとき、リンクを作成しない
349                         $line->{chname} = $line->{chtxt};
350                         $line->{chname_link} = qq {$line->{chname}</a>};
351                 }
352                 else {
353                         $line->{chname_link} = qq {<a href="rectool.pl?mode=program&amp;chtxt=$line->{chtxt}">$line->{chname}</a>};
354                 }
355                 $line->{title} = 'タイトルなし' if ( !$line->{title} );
356                 $line->{tr_style} = '';
357                 $line->{title_2} = '';
358                 my $unix_b = str2datetime( $line->{btime} );
359                 my $unix_e = str2datetime( $line->{etime} );
360
361                 my $btime = $unix_b->strftime( '%Y%m%d%H%M%S' );
362                 my $etime = $unix_e->strftime( '%Y%m%d%H%M%S' );
363                 if ( $extra and $line->{type} =~ /^search_|^reserve_(?!running)/ ) {
364                         #my @ary = $dbh->selectrow_array(
365                         #       "SELECT title, exp FROM epg_timeline 
366                         #       WHERE channel = '$line->{chname}' 
367                         #       AND start = '$btime' 
368                         #       AND stop  = '$etime' ");
369                         #my @ary = ( $line->{epgtitle}, $line->{epgexp} );
370                         my ( $epgtitle, $epgexp ) = ( $line->{epgtitle}, $line->{epgexp} );
371
372                         if ( $epgtitle ) {
373                                 $epgtitle =~ s/無料≫//;
374
375                                 if ( $epgtitle ne $line->{title} ) {
376                                         # epgtitleとtitleが一致しない
377                                         # []に囲まれた部分を除去して比較
378                                         my @brackets = $line->{title} =~ /(\[.+\])+/;
379                                         my $epgtitle_nobrackets = $epgtitle;
380                                         my $title_nobrackets = $line->{title};
381                                         if ( @brackets && $epgtitle =~ /(\[.+\])+/ >= @brackets ) {
382                                                 foreach ( @brackets ) {
383                                                         $epgtitle_nobrackets =~ s/\Q$_\E//;
384                                                 }
385                                         }
386                                         $title_nobrackets =~ s/(\[.+\])+//;
387                                         if ( !scalar $epgtitle_nobrackets =~ s/\Q$title_nobrackets\E// ) {
388                                                 # epgtitleにtitleが含まれていない
389                                                 my $href  = qq {<a href="rectool.pl?mode=edit&amp;id=$line->{id}&amp;suggest=auto">自動検索</a>};
390                                                 $epgtitle = qq {<span style="color: #FF4000">$epgtitle■$href■</span>};
391                                         }
392                                         else {
393                                                 # epgtitleにtitleが含まれている
394                                                 $epgtitle = $epgtitle_nobrackets;
395                                         }
396                                 }
397                                 else {
398                                         # epgtitleとtitleが一致している
399                                         $epgtitle = '説明';
400                                 }
401
402                                 $line->{title_2} = qq {<div style="float: right; cursor: help" title="$epgexp">$epgtitle</div>};
403                         }
404                         else {
405                                 # epgtitleがない
406                                 my $href    = qq {<a href="rectool.pl?mode=edit&amp;id=$line->{id}&amp;suggest=auto">自動検索</a>};
407                                 $line->{title_2}  = qq {<span style="float: right; color: #FF0000">■$href■</span>};
408                                 $line->{tr_style} = qq {style="background-color: #A0A0A0"};
409                         }
410                 }
411
412                 my ( $begin, $end, $diff ) = &str2readable( $unix_b, $unix_e );
413
414                 my $hr = '';
415                 if ( 
416                         $line->{type} eq 'reserve_running' 
417                                 &&
418                         $unix_b->epoch <= time && time <= $unix_e->epoch
419                 )
420                 {
421                         $percent = int( ( 100 * ( time - $unix_b->epoch ) ) / ( $unix_e->epoch - $unix_b->epoch ) );
422                         $hr .= qq {<hr style="margin: 0 auto 0 0; height: 4px; width: $percent%;};
423                         $hr .= qq { background-color: blue; border: none" title="$percent%">};
424                 }
425
426                 $line->{title} = qq {<a href="rectool.pl?mode=edit&amp;id=$line->{id}">$line->{title}</a>};
427                 #$line->{title} = qq {<div style="float: left">$line->{title}</div>} if ( $line->{title_2} );
428                 $HTML .= qq {<tr align="center" $line->{tr_style}>\n};
429                 $HTML .= qq {<td><input type="checkbox" name="id" value="$line->{id}"></td>\n};
430                 $HTML .= qq {<td>$line->{id}</td>\n};
431                 $HTML .= qq {<td>$type</td>\n};
432                 $HTML .= qq {<td>$line->{chname_link}</td>\n};
433                 $HTML .= qq {<td align="left" style="white-space: normal">$line->{title}$line->{title_2}</td>\n};
434                 $HTML .= qq {<td>$begin</td>\n<td>$end</td>\n};
435                 $HTML .= qq {<td>$hr$diff</td>\n};
436                 $HTML .= qq {<td>$line->{opt}</td>\n<td>$line->{deltaday}</td>\n<td>$line->{deltatime}</td>\n<td>$line->{counter}</td>\n};
437                 $HTML .= qq {</tr>\n};
438         }
439         $HTML .= qq {</table>\n};
440         #$HTML .= qq {<input type="submit" name="edit" value="編集(要JS)">\n};
441         $HTML .= qq {<input type="submit" name="delete" value="削除">\n</div>\n</form>\n};
442         goto end;
443 }
444
445 ################ mode=graph ################
446
447 if ( $mode eq 'graph' ) {
448
449         my $date = $params{ 'date' };
450
451         if ( $date )
452         {
453                 print "Content-Type: image/svg+xml\n\n";
454
455                 require SVG;
456                 $date = Date::Simple->new( split /-/, $date );
457                 $graph_bgn = $date->format('%Y-%m-%d');
458                 $graph_end = $date->next->format('%Y-%m-%d');
459                 $day = $date->day;
460                 $today = $date eq Date::Simple->today() ? 1 : 0;
461
462                 $tuner{terrestrial} = $cfg->param( 'env.te_max'   );# 2;
463                 $tuner{satellite}   = $cfg->param( 'env.bscs_max' );# 2;
464                 $tuner{all} = $tuner{terrestrial} + $tuner{satellite};
465                 $hours = 24;
466                 $width = 30 * $hours;
467                 my %category_color = map { $_->{name}, $_->{color} } values %category;
468
469                 $svg = new SVG( width => 820, height => $tuner{all} * 20 + 40 );
470                 $svg->rectangle( 'x' => 40, 'y' => 20, 
471                         width => $width + 20, height => $tuner{all} * 20 + 10, 
472                         rx => 15, ry => 15, 
473                         style => { stroke => 'blue', fill => 'white' } );
474                 for ( 1..$tuner{terrestrial} ) {
475                         $svg->text( 'x' => 10, 'y' => ( $_ + 1 ) * 20 )
476                                 ->cdata( "T$_" );
477                 }
478                 for ( 1..$tuner{satellite} ) {
479                         $svg->text( 'x' => 10, 'y' => ( $_ + $tuner{terrestrial} + 1 ) * 20 )
480                                 ->cdata( "S$_" );
481                 }
482                 for ( 0..$hours ) {
483                         $svg->text( 'x' => $_ * 30 + 65, 'y' => 15, 
484                                 style => { 'text-anchor' => 'middle' } )
485                                 ->cdata( sprintf( '%02d', $_ ) ) if ( $_ < $hours );
486                         # $svg->line( ); # can't be used when required
487                         $svg->tag( 'line', x1 => $_ * 30 + 50, x2 => $_ * 30 + 50, y1 => 30, y2 => $tuner{all} * 20 + 20, 
488                                 style => { stroke => 'gray' } );
489                 }
490                 for ( 1..$tuner{all} ) {
491 #                       $svg->tag( 'line', x1 =>50, x2 => 50 + $width, y1 => $_ * 20 + 10, y2 => $_ * 20 + 10, 
492 #                               style => { stroke => 'gray' } );
493 #                       $svg->rectangle( 'x' => 50, 'y' => $_ * 20 + 10, width => $width, height => 10 );
494                         $svg->rectangle( 'x' => 50, 'y' => $_ * 20 + 14, width => $width, height => 2 );
495                 }
496                 if ( $today ) {
497                         require Time::Simple;
498                         my $time = Time::Simple->new();
499                         my $x = ( $time->hours * 60 + $time->minutes ) * 0.5 + 50;
500                         $svg->tag( 'line', x1 => $x, x2 => $x, y1 => 30, y2 => $tuner{all} * 20 + 20, 
501                                 style => { stroke => 'red', 'fill-opacity' => '1.0' } );
502                 }
503                 my $ary_ref = $dbh->selectall_arrayref(
504                         #       epg_timeline.channel = timeline.chtxt && 
505                         "SELECT id, title, chtxt, btime, etime, epgcategory, opt FROM timeline 
506                         WHERE type IN $type_user_made 
507                         AND 
508                         (
509                                 '$graph_bgn 00:00' <= btime AND btime <  '$graph_end 00:00'
510                                         OR
511                                 '$graph_bgn 00:00' <  etime AND etime <= '$graph_end 00:00'
512                         )
513                         ORDER BY btime"
514                         , {Slice=>{}}
515                 );
516
517                 foreach my $bctype ( '\d+_', 'S_' ) {
518                         my $tuner = $bctype eq '\d+_' ? $tuner{terrestrial} : $tuner{satellite};
519                         my @ary_ref = grep { $_->{chtxt} =~ /$bctype/ } @{ $ary_ref };
520                         my @y_drawn = ('') x $tuner;
521                         foreach my $line ( @ary_ref ) {
522                                 @start = $line->{btime} =~ /(.{4})-(.{2})-(.{2}) (.{2}):(.{2})/;
523                                 @stop  = $line->{etime} =~ /(.{4})-(.{2})-(.{2}) (.{2}):(.{2})/;
524                                 $start = ( ( $day == $start[2] ? 0 : 24 * 60 ) + $start[3] * 60 + $start[4] ) * 0.5;
525                                 $stop  = ( ( $day == $stop [2] ? 0 : 24 * 60 ) + $stop [3] * 60 + $stop [4] ) * 0.5;
526                                 $start = 0      if ( $start < 0 || $day > $start[2] ); # 月の変わり目はスルー
527                                 $stop  = $width if ( $stop  > $width );
528                                 $begin = $line->{btime};
529                                 $end   = $line->{etime};
530
531                                 my @ary = grep { ( $_->{etime} cmp $line->{btime} ) > 0 and ( $_->{btime} cmp $line->{etime} ) < 0 and $_->{id} != $line->{id} } @ary_ref;
532                                 foreach my $i ( 0..$tuner - 1 ) {
533                                         next if ( ( $y_drawn[$i] cmp $line->{btime} ) > 0 );
534                                         #for ( 'chtxt', 'btime', 'etime' ) {
535                                         #       $f = 0 if ( $line->{$_} ne $ary[$i]->{$_} );
536                                         #}
537                                         $line->{slot} = $i;
538                                         $y_drawn[$i] = $line->{etime};
539                                         last;
540                                 }
541                                 my ( $r, $g, $b ) = ( 0, 0, 0 );
542                                 $r += 255 if ( $line->{opt} =~ /a/ );
543                                 $g += 255 if ( $line->{opt} =~ /H/ );
544                                 $b += 255 if ( $line->{opt} =~ /I/ );
545                                 if ( $r + $g + $b == 255 * 3 ){
546                                         $r = 0;
547                                         $g = 255;
548                                         $b = 255;
549                                 }
550                                 if ( $r + $g + $b == 0 ){
551                                         $r = $g = $b = 128;
552                                 }
553                                 my %escaped = ( '&' => 'amp', '<' => 'lt', '>' => 'gt', '"' => 'quot' );
554                                 sub html_escape{
555                                         my $str = shift or return;
556                                         my $result = '';
557                                         $result .= $escaped{$_} ? '&' . $escaped{$_} . ';' : $_
558                                                 for (split //, $str);
559                                         $result;
560                                 }
561                                 $svg->anchor(
562                                         -href  => "rectool.pl?mode=edit&amp;id=$line->{id}",
563                                         target => '_blank',
564                                         -title => html_escape( $line->{title} ),
565                                 )->rectangle( 
566                                         'x' => 50 + $start, 
567                                         'y' => 30 + ( $bctype eq '\d+_' ? 0 : $tuner{terrestrial} * 20 ) + $line->{slot} * 20, 
568                                         width  => $stop - $start, 
569                                         height => 10, 
570                                         style  => { fill => $category_color{$line->{epgcategory}} || $category_color{'その他'} } );
571                                         #style  => { fill => "rgb($r,$g,$b)" } );
572                         }
573                 }
574                 my $xml = $svg->xmlify;
575                 utf8::encode( $xml );
576                 print $xml;
577                 #warningsToBrowser(true);
578                 exit;
579         }
580         else
581         {
582                 $HTML =~ s/%HTML_TITLE_OPT%/ - Schedule Viewer - Graphical/;
583                 $HTML .= qq {<div style="float: left">\n};
584                 # $base64 = encode_base64( $svg->xmlify );
585                 # $HTML .= qq {<object data="data:image/svg+xml;base64,$base64">\n</object>\n};
586                 $HTML .= qq {予約状況一覧です。T1,T2は地上波、S1,S2はBS/CSを示しています。<br>\n};
587                 $HTML .= qq {SVGが利用可能なブラウザでご覧ください。<br>\n};
588                 $HTML .= qq {色とジャンルの対応\n};
589                 map { 
590                         $HTML .= qq {<span style="background: $_->{color}; top: 10px; left: 250px;">$_->{name}</span>\n};
591                 } values %category;
592                 $HTML .= qq {<br>\n};
593
594                 $ary_ref = $dbh->selectcol_arrayref(
595                         "SELECT DISTINCT DATE( btime ) 
596                         FROM timeline 
597                         WHERE type in $type_user_made 
598                         ORDER BY btime"
599                 );
600                 foreach my $date ( @{ $ary_ref } ) {
601                         my @date = $date =~ /(.{4})-(.{2})-(.{2})/;
602                         my $dn = DateTime->new( year => $date[0], month => $date[1], day => $date[2], locale => 'ja_JP' )->day_name;
603                         #utf8::encode( $dn );
604                         $HTML .= qq {$date[1]/$date[2]($dn)の予約状況<br>\n};
605                         # <img src="">
606                         $HTML .= qq {<object type="image/svg+xml" data="rectool.pl?mode=graph&amp;date=$date" width="820">\n};
607                         $HTML .= qq {SVG Image $date\n</object>\n<br>\n};
608
609                         $date2 = Date::Simple->new( @date )->next->format('%Y-%m-%d');
610                         my $ary_ref = $dbh->selectall_arrayref(
611                                 "SELECT chtxt, title, btime, etime FROM timeline 
612                                 WHERE '$date 00:00' <= btime AND etime <= '$date2 01:00'
613                                 ORDER BY btime"
614                         );
615
616                         foreach my $line ( @{ $ary_ref } ) {
617                                 #$HTML .= qq {$line->[0] $line->[1] $line->[2] $line->[3]<br>\n};
618                         }
619
620                 }
621
622                 goto end;
623         }
624 }
625
626 ################ mode=atom ################
627
628 if ( $mode eq 'atom' ) {
629         require XML::Atom::Feed;
630         require XML::Atom::Entry;
631
632         my $recording_count = $encoding_count = $jbk_count = 0;
633         my $ary_ref = $dbh->selectall_arrayref(
634                 "SELECT chtxt, title, btime, etime, opt 
635                 FROM timeline 
636                 WHERE type = 'reserve_running' ");
637         foreach my $line ( @{$ary_ref} ) {
638                 my ( $begin, $end, $diff ) = &str2readable( $line->[2], $line->[3] );
639                 $recording_status .= qq {$line->[0] $line->[1] $begin - $end $diff $line->[4]<br />\n};
640                 $recording_count++;
641         }
642         $ary_ref = $dbh->selectall_arrayref(
643                 "SELECT chtxt, title, btime, etime, opt 
644                 FROM timeline 
645                 WHERE type = 'convert_ts_mp4_running' ");
646         foreach my $line ( @{$ary_ref} ) {
647                 my ( $begin, $end, $diff ) = &str2readable( $line->[2], $line->[3] );
648                 $encoding_status .= qq {$line->[0] $line->[1] $begin - $end $diff $line->[4]<br />\n};
649                 $encoding_count++;
650         }
651         $ary_ref = $dbh->selectall_arrayref(
652                 "SELECT id, chtxt, title, btime, etime 
653                 FROM auto_timeline_keyword " );
654         foreach my $line ( @{$ary_ref} ) {
655                 my ( $begin, $end, $diff ) = &str2readable( $line->[3], $line->[4] );
656                 $jbk_status .= qq {$line->[0] $line->[1] $line->[2] $begin - $end $diff<br />\n};
657                 $jbk_count++;
658         }
659
660         my $feed = XML::Atom::Feed->new( Version => 1.0 );
661         $feed->title('Rec10 フィード');
662
663         my $entry = XML::Atom::Entry->new( Version => 1.0 );
664         $entry->title("Rec10 録画状況 ($recording_count)");
665         $entry->id('tag:recording_status');
666         $entry->content($recording_status);
667         $entry->add_link(str_to_link( './rectool.pl?mode=schedule' ) );
668         $feed->add_entry($entry);
669
670         $entry = XML::Atom::Entry->new( Version => 1.0 );
671         $entry->title("Rec10 縁故状況 ($encoding_count)");
672         $entry->id('tag:encoding_status');
673         $entry->content($encoding_status);
674         $entry->add_link(str_to_link( './rectool.pl?mode=schedule' ) );
675         $feed->add_entry($entry);
676
677         $entry = XML::Atom::Entry->new( Version => 1.0 );
678         $entry->title("Rec10 地引状況 ($jbk_count)");
679         $entry->id('tag:jbk_status');
680         $entry->content($jbk_status);
681         $entry->add_link(str_to_link( './rectool.pl?mode=jbk' ) );
682         $feed->add_entry($entry);
683
684         my $xml = $feed->as_xml;
685         print "Content-Type: application/atom+xml\n\n";
686         print $xml;
687         exit;
688
689         sub str_to_link {
690                 my $link = XML::Atom::Link->new( Version => 1.0 );
691                 $link->type('text/html');
692                 $link->rel('alternate');
693                 $link->href(shift);
694                 return $link;
695         }
696 }
697
698 ################ mode=edit ################
699
700 if ( $mode eq 'edit' ) {
701         my $id = $params{ 'id' };
702
703         $HTML =~ s/%HTML_TITLE_OPT%/ - Schedule Editor/;
704         $HTML .= qq {<div style="float: left">\n};
705
706         $script = <<EOM;
707                 <script type="text/javascript" src="http://www.enjoyxstudy.com/javascript/dateformat/dateformat.js">
708                 </script>
709                 <script type="text/javascript">
710                 function setType(value){
711                         var index = document.reserve.type.selectedIndex;
712                         var value = document.reserve.type[index].value;
713                         if ( value == 'search_everyday' ) {
714                                 document.reserve.deltaday.value  = 7;
715                                 document.reserve.deltatime.value = 3;
716                         }
717                         if ( value == 'convert_b25_ts' || value == 'convert_ts_mp4' ){
718                                 var date       = new Date();
719                                 var dateFormat = new DateFormat("yyyy-MM-dd HH:mm:ss");
720                                 var minutes    = date.getMinutes();
721                                 minutes = minutes - minutes % 5 + 10;
722                                 date.setMinutes(minutes, 0, 0);
723                                 document.reserve.begin.value = dateFormat.format(date);
724                                 date.setSeconds( date.getSeconds() + 3600 );
725                                 document.reserve.end.value   = dateFormat.format(date);
726                         }
727                 }
728                 function setSuggest(start, stop){
729                         document.reserve.begin.value = start;
730                         document.reserve.end.value   = stop;
731                 }
732                 function shiftEndTime(value){
733                         var dateFormat = new DateFormat("yyyy-MM-dd HH:mm:ss");
734                         var date = dateFormat.parse(document.reserve.end.value || document.reserve.begin.value);
735                         date.setSeconds( date.getSeconds() + value );
736                         document.reserve.end.value = dateFormat.format(date);
737                 }
738                 </script>
739 EOM
740         $script =~ s/^\t{2}//gm;
741         $HTML =~ s/%SCRIPT%/$script/;
742
743         $HTML .= "スケジュール編集画面です。<br>\n";
744         $HTML .= "実装がとても適当なので、利用には細心の注意を払ってください。<br>\n<br>\n";
745         if ( $id ) {
746                 # 予約の編集
747                 &parse_program();
748                 $button_bgn = $button_end = '';
749         }
750         else {
751                 # 新規予約
752                 $type = 'reserve_flexible';
753                 $counter = -1;
754                 $datetime_now = DateTime->now( time_zone => $tz )->set_second( 0 )->add( minutes => 1)->strftime( '%Y-%m-%d %H:%M:%S' );
755                 $button_bgn = qq{<button type="button" onClick="document.reserve.begin.value='$datetime_now'">現在</button>\n<br>\n};
756                 $button_end = 
757                          qq{<button type="button" onClick="document.reserve.end.value=document.reserve.begin.value">一致</button>}
758                         .qq{<button type="button" onClick="shiftEndTime(300);">+5m</button>}
759                         .qq{<button type="button" onClick="shiftEndTime(1800);">+30m</button>};
760         }
761
762         if ( $params{ 'suggest' } eq 'auto' ) {
763                 my @btime = $begin =~ /(.{4})-(.{2})-(.{2}) (.{2}):(.{2}):(.{2})/;
764                 my @etime = $end   =~ /(.{4})-(.{2})-(.{2}) (.{2}):(.{2}):(.{2})/;
765                 my $btime = DateTime->new(
766                         year => $btime[0], month  => $btime[1], day    => $btime[2],
767                         hour => $btime[3], minute => $btime[4], second => $btime[5], 
768                 );
769                 my $etime = DateTime->new(
770                         year => $etime[0], month  => $etime[1], day    => $etime[2],
771                         hour => $etime[3], minute => $etime[4], second => $etime[5], 
772                 );
773                 my %hash = &sqlgetsuggested( $btime, $etime );
774
775                 $HTML .= qq {可能性のある番組<br>\n};
776                 $HTML .= qq {<table summary="suggesttable" border=1 cellspacing=0>\n<tr>\n};
777                 $HTML .= qq {<th>優先度</th>\n};
778                 $HTML .= qq {<th>タイトル</th>\n};
779                 $HTML .= qq {<th>開始時刻</th>\n};
780                 $HTML .= qq {<th>終了時刻</th>\n};
781                 $HTML .= qq {<th>説明</th>\n};
782                 $HTML .= qq {<th>適用</th>\n};
783                 $HTML .= qq {</tr>\n};
784
785                 foreach my $key (sort keys %hash){
786                         my $val = $hash{$key};
787                         foreach my $val ( @{$val} ) {
788                                 my $style = qq {style="white-space: nowrap"};
789                                 $val->[0] =~ s/(.{4})(.{2})(.{2})(.{2})(.{2})(.{2})/$1-$2-$3 $4:$5:$6/;
790                                 $val->[1] =~ s/(.{4})(.{2})(.{2})(.{2})(.{2})(.{2})/$1-$2-$3 $4:$5:$6/;
791                                 $HTML .= qq {<tr>\n<td>$key</td>\n<td>$val->[2]</td>\n};
792                                 $HTML .= qq {<td $style>$val->[0]</td>\n<td $style>$val->[1]</td>\n<td>$val->[3]</td>\n};
793                                 $HTML .= qq {<td><button onClick="setSuggest('$val->[0]','$val->[1]');">適用</button></td>\n</tr>\n};
794                         }
795                 }
796                 $HTML .= qq {</table>\n<br>\n};
797         }
798
799         my $len = length $id;
800         $HTML .= qq {<form method="get" action="rectool.pl" name="reserve">\n};
801         $HTML .= qq {<input type="hidden" name="mode" value="change">\n};
802         $HTML .= qq {<input type="hidden" name="mode_sub" value="update">\n};
803         $HTML .= qq {<input type="hidden" name="id" value="$id">\n};
804         $HTML .= qq {ID\n<input type="text" name="id" value="$id" size=$len disabled>\n};
805         $HTML .= qq {タイプ\n<select name="type" onChange="setType();">\n};
806         foreach my $key ( keys %type ) {
807                 next if ( $key !~ /^search|^reserve_flexible$|^reserve_fixed$|^convert_b25_ts$|^convert_ts_mp4$|^$type$/ );
808                 $value = $type{$key};
809                 if ( $key eq $type ) {
810                         $HTML .= qq {<option value="$key" selected>$value</option>\n};
811                 }
812                 else {
813                         $HTML .= qq {<option value="$key">$value</option>\n};
814                 }
815         }
816         $HTML .= qq {</select>\n};
817
818         $HTML .= qq {チャンネル\n<select name="chtxt">\n};
819         # 移動縁故など、チャンネルリスト内にchtxtが存在しない場合に備えて
820         $chtxt_0_chname{$chtxt} = $chname || $chtxt if ( !$chtxt_0_chname{$chtxt} );
821         foreach my $key ( sort keys %chtxt_0_chname ) {
822                 if ( $key eq $chtxt || $key eq $chtxt_0 ) {
823                         $HTML .= qq {<option value="$key" selected>$chtxt_0_chname{$key}</option>\n};
824                 }
825                 else {
826                         $HTML .= qq {<option value="$key">$chtxt_0_chname{$key}</option>\n};
827                 }
828         }
829         $HTML .= qq {</select><br>\n};
830         $HTML .= qq {タイトル\n<input type="text" name="title" value="$title" size=64><br>\n};
831         $HTML .= qq {開始時刻\n<input type="text" name="begin" value="$begin" maxlength=19 size=24>\n};
832         $HTML .= $button_bgn;
833         $HTML .= qq {終了時刻\n<input type="text" name="end" value="$end" maxlength=19 size=24>\n};
834         $HTML .= $button_end . "<br>\n";
835         $HTML .= qq {隔日周期\n<input type="text" name="deltaday" value="$deltaday" maxlength=2  size=2 >\n};
836         $HTML .= qq {時刻誤差\n<input type="text" name="deltatime" value="$deltatime" maxlength=2  size=2 >\n};
837         $HTML .= qq {オプション\n<input type="text" name="opt" value="$opt">\n};
838         $HTML .= qq {回数\n<input type="text" name="counter" value="$counter" size=2 >\n};
839         $HTML .= qq {<input type="submit" name="update" value="更新">\n</form>\n};
840 }
841
842 ################ mode=change ################
843
844 if ( $mode eq 'change' ) {
845         @id     = $q->param( 'id' );
846
847         $HTML =~ s/%HTML_TITLE_OPT%/ - Change/;
848         $HTML .= qq {<div style="float: left">\n};
849
850         if ( $params{ 'delete' } )
851         {
852                 if ( @id ) {
853                         foreach my $id ( @id ) {
854                                 $dbh->do( "DELETE FROM timeline WHERE id = '$id'" );
855                         }
856                         $HTML .= "削除しました。<br>\n5秒後に予約確認画面に移動します。<br>\n";
857                         $HTML =~ s|%REFRESH%|<meta http-equiv="refresh" content="5; url=rectool.pl?mode=schedule">|;
858                         goto end;
859                 }
860         }
861         if ( $params{ 'update' } )
862         {
863                 $type      = $params{ 'type' };
864                 $chtxt     = $params{ 'chtxt' };
865                 $title     = $params{ 'title' };
866                 $begin     = $params{ 'begin' };
867                 $end       = $params{ 'end' };
868                 $deltaday  = $params{ 'deltaday' };
869                 $deltatime = $params{ 'deltatime' };
870                 $opt       = $params{ 'opt' };
871                 $counter   = $params{ 'counter' };
872                 $id        = $id[0];
873                 if ( $id ) {
874                         $dbh->do( 
875                                 "UPDATE timeline SET type = '$type', chtxt = '$chtxt', title = '$title', 
876                                 btime = '$begin', etime = '$end', 
877                                 deltaday = '$deltaday', deltatime = '$deltatime', opt = '$opt', counter = '$counter' 
878                                 WHERE id = '$id'" 
879                         );
880                 }
881                 else {
882                         $dbh->do( 
883                                 "INSERT INTO timeline ( type, chtxt, title, btime, etime, deltaday, deltatime, opt, counter ) 
884                                 VALUES ( '$type', '$chtxt', '$title', '$begin', '$end', '$deltaday', '$deltatime', '$opt', '$counter' )" 
885                         );
886                 }
887                 $HTML .= "更新しました。<br>\n5秒後に予約確認画面に移動します。<br>\n";
888                 $HTML =~ s|%REFRESH%|<meta http-equiv="refresh" content="5; url=rectool.pl?mode=schedule">|;
889                 goto end;
890         }
891         if ( $mode_sub eq 'proc' ) {
892                 my $type  = $params{ 'type' };
893                 my $chtxt = $params{ 'chtxt' } || 'nhk-k';
894                 my $title = $params{ 'title' };
895                 my @opt   = $q->param( 'opt' );
896                 my $opt   = join '', @opt;
897
898                 my $datetime_now = DateTime->now( time_zone => $tz )->set_second( 0 )->add( minutes => 10);
899                 my $sql_type = $type_suggest{$type};
900                 my $begin = $datetime_now->strftime( '%Y-%m-%d %H:%M:%S' );
901                 $datetime_now = $datetime_now->add( minutes => 60 );
902                 my $end = $datetime_now->strftime( '%Y-%m-%d %H:%M:%S' );
903
904                 $dbh->do( 
905                         "INSERT INTO timeline ( type, chtxt, title, btime, etime, opt ) 
906                         VALUES ( '$sql_type', '$chtxt', '$title', '$begin', '$end', '$opt' )"
907                 );
908
909                 goto end;
910         }
911         if ( $mode_sub eq 'move' ) {
912                 my $mode_sub2  = $params{ 'mode_sub2' };
913                 my $title      = $params{ 'title' };
914                 my $response;
915
916                 $ENV{'LANG'} = 'ja_JP.UTF-8';
917                 if ( $mode_sub2 eq 'predict' ) {
918                         $HTML .= "移動後のシミュレーション結果です。\n<br>";
919                         eval '$response = `python26 ' . $cfg->param( 'path.rec10' ) . "/classify.py -s '$title'`";
920                 }
921                 elsif ( $mode_sub2 eq 'exec' ) {
922                         eval '$response = `python26 ' . $cfg->param( 'path.rec10' ) . "/classify.py -e '$title'`";
923                 }
924                 utf8::decode( $response );
925                 $HTML .= $response;
926
927                 goto end;
928         }
929         if ( $mode_sub eq 'setting' ) {
930                 my $jbk     = $params{ 'jbk' }     || '0';
931                 my $bayes   = $params{ 'bayes' }   || '0';
932                 my $del_tmp = $params{ 'del_tmp' } || '0';
933                 my $opt     = $params{ 'opt' }     || '';
934                 my $user    = $params{ 'user' }    || '';
935                 my $pass    = $params{ 'pass' }    || '';
936
937                 $dbh->do( 
938                         "UPDATE in_settings SET auto_jbk = '$jbk', auto_bayes = '$bayes', 
939                         auto_del_tmp = '$del_tmp', auto_opt = '$opt'"
940                 );
941
942                 goto end;
943         }
944         if ( $mode_sub eq 'fixstatus' ) {
945                 my $key = $params{ 'terec'  } ? 'terec'  : $params{ 'bscsrec' } ? 'bscsrec' : 
946                           $params{ 'b252ts' } ? 'b252ts' : $params{ 'ts2avi'  } ? 'ts2avi'  : '';
947
948                 $dbh->do( 
949                         "UPDATE in_status SET $key = 0"
950                 );
951
952                 goto end;
953         }
954
955 }
956
957 ################ mode=confirm ################
958
959 if ( $mode eq 'confirm' ) {
960         if ( $mode_sub eq 'reserve' ) {
961                 $HTML =~ s/%HTML_TITLE_OPT%/ - Reserver/;
962                 $HTML .= qq {<div style="float: left">\n};
963                 &parse_program();
964
965                 my $duration = ( str2datetime( $end ) - str2datetime( $begin ) )->delta_minutes;
966                 $HTML .= "番組名:$title<br>\nチャンネル:$chname<br>\n放送継続時間:$duration 分<br>\n番組内容:$desc<br>\nジャンル:$category<br>\n";
967                 if ( $longdesc ) {
968                         $longdesc =~ s/\\n/<br>\n/gs;
969                         $HTML .= "番組内容(長):$longdesc<br>\n";
970                 }
971                 my $error = &check_error();
972                 if ( $error )
973                 {
974                         # エラー
975
976                         $ary_ref = $dbh->selectall_arrayref(
977                                 "SELECT start, stop FROM epg_timeline WHERE channel = '$chtxt' AND title = '$title' "
978                         );
979                         if ( $error != 1 ) {
980                                 $HTML .= "同一の番組の他の放送予定です。<br>\n";
981                                 foreach my $line ( @{$ary_ref} ) {
982                                         $begin = $line->[0];
983                                         $end   = $line->[1];
984                                         $begin =~ s/(.{4})(.{2})(.{2})(.{2})(.{2})(.{2})/$1-$2-$3 $4:$5:$6/;
985                                         $end   =~ s/(.{4})(.{2})(.{2})(.{2})(.{2})(.{2})/$1-$2-$3 $4:$5:$6/;
986                                         $overlap = &get_overlap() >= 2 ? '不可能' : 
987                                                 qq {<a href="rectool.pl?mode=confirm&amp;mode_sub=reserve&amp;chtxt=$chtxt&amp;start=$line->[0]&amp;stop=$line->[1]">可能</a>};
988                                         $HTML .= "開始:$begin\n終了:$end\n録画は$overlap<br>\n";
989                                 }
990                         }
991                 }
992                 else {
993                         $HTML .= "録画予約の詳細設定を行ってください。<br>\n";
994                         $HTML .= qq {<form method="get" action="rectool.pl">\n};
995                         $HTML .= qq {<input type="hidden" name="mode"  value="reserve">\n};
996                         $HTML .= qq {<input type="hidden" name="chtxt" value="$chtxt">\n};
997                         $HTML .= qq {<input type="hidden" name="start" value="$start">\n};
998                         $HTML .= qq {<input type="hidden" name="stop"  value="$stop">\n};
999                         $HTML .= qq {<input type="hidden" name="title" value="$title">\n} if ( $params{ 'title' } );
1000                         &draw_form_opt( 'reserve' );
1001                         $HTML .= qq {<input type="submit" value="予約">\n</form>\n};
1002                 }
1003                 goto end;
1004         }
1005         # End of $mode_sub eq 'reserve';
1006
1007         if ( $mode_sub eq 'proc' ) {
1008                 my    $type  = $params{ 'type' };
1009                 local $chtxt = $params{ 'chtxt' };
1010                 my    $title = $params{ 'title' };
1011                 local $opt   = $params{ 'opt' };
1012                 utf8::decode( $title );
1013
1014                 $HTML .= "詳細設定を行ってください。<br>\n";
1015                 $HTML .= "タイトル:$title\n<br>\n";
1016
1017                 $HTML .= qq {<form method="get" action="rectool.pl">\n};
1018                 $HTML .= qq {<input type="hidden" name="mode"     value="change">\n};
1019                 $HTML .= qq {<input type="hidden" name="mode_sub" value="proc">\n};
1020                 $HTML .= qq {<input type="hidden" name="type"     value="$type">\n};
1021                 $HTML .= qq {<input type="hidden" name="title"    value="$title">\n};
1022                 &draw_form_channel( 'nonone' );
1023                 &draw_form_opt();
1024                 $HTML .= qq {<input type="submit" value="予約">\n</form>\n};
1025                 goto end;
1026         }
1027 }
1028
1029 ################ mode=reserve ################
1030
1031 if ( $mode eq 'reserve' ) {
1032         $HTML .= qq {<div style="float: left">\n};
1033         &parse_program();
1034         $title = $params{ 'title' } if ( !$title );
1035         @opt = $q->param( 'opt' );
1036         $opt = join '', @opt;
1037         my ( $deltaday, $deltatime );
1038
1039         if ( $params{'every'} eq '1' ) {
1040                 $type = 'search_everyday';
1041                 ( $changed_t ) = $title =~ /(.*)#/;
1042                 $title = $changed_t if ( $changed_t );
1043                 ( $changed_t ) = $title =~ /(.*)第/;
1044                 $title = $changed_t if ( $changed_t );
1045                 ( $changed_t ) = $title =~ /(.*)▽/;
1046                 $title = $changed_t if ( $changed_t );
1047                 $title =~ s/「.*」//;
1048                 $title =~ s/<.*>//;
1049                 $title =~ s/(.*)//;
1050                 $title =~ s/\[新\]//;
1051                 $title =~ s/無料≫//;
1052                 $title =~ s/\s*$//;
1053                 $deltaday  = 7;
1054                 $deltatime = 3;
1055         }
1056         else {
1057                 $type = 'reserve_flexible';
1058         }
1059         $chtxt = $chtxt_0 if ( $chtxt_0 );
1060         if ( !&check_error ) {
1061                 $dbh->do( 
1062                         "INSERT INTO timeline ( type, chtxt, title, btime, etime, opt, deltaday, deltatime ) 
1063                         VALUES ( '$type', '$chtxt', '$title', '$begin', '$end', '$opt', '$deltaday', '$deltatime' )" 
1064                 );
1065         }
1066         $HTML .= "録画予約を実行しました。<br>\n5秒後にトップへ移動します。<br>\n";
1067         $HTML =~ s|%REFRESH%|<meta http-equiv="refresh" content="5; url=rectool.pl">|;
1068         goto end;
1069 }
1070
1071 ################ mode=program ################
1072
1073 if ( $mode eq 'program' ) {
1074         &draw_form();
1075
1076         $HTML =~ s/%HTML_TITLE_OPT%/ - Program Viewer/;
1077         $unix = DateTime->now( time_zone => $tz )->strftime( '%Y%m%d%H%M%S' );
1078         $sql = 
1079                 "SELECT channel, epg_ch.chname, start, stop, title, category 
1080                 FROM epg_timeline 
1081                 INNER JOIN epg_ch ON epg_timeline.channel = epg_ch.chtxt 
1082                 WHERE $unix <= stop %CH% %DATE% %CATEGORY% %KEY% ORDER BY start";
1083
1084         if ( $chtxt ) {
1085                 my $ch;
1086                 if ( $chtxt =~ /^\d+(_0)?$/ ) {
1087                         # teはxx_yyy形式であるため
1088                         $chtxt =~ s/_0//;
1089                         $ch = "AND channel LIKE '$chtxt\_%'";
1090                 }
1091                 else {
1092                         $ch = "AND channel = '$chtxt'";
1093                 }
1094                 $sql =~ s/%CH%/$ch/;
1095         }
1096         if ( $date_sel ) {
1097                 $date_1 = $date_sel . '000000';
1098                 $date_2 = Date::Simple->new( $date_sel =~ /(.{4})(.{2})(.{2})/ )->next->format('%Y%m%d') . '000000';
1099                 my $date = "AND '$date_1' <= stop AND start <= '$date_2'";
1100                 $sql =~ s/%DATE%/$date/;
1101         }
1102         if ( $category_sel ) {
1103                 # 一時的
1104                 #       $category_tmp = $category{$category_sel} . $category_sel;
1105                 my $category = "AND category = '$category{$category_sel}->{name}'";
1106                 $sql =~ s/%CATEGORY%/$category/;
1107         }
1108         if ( $key ) {
1109                 my $key = "AND TITLE LIKE '%$key%'";
1110                 $sql =~ s/%KEY%/$key/;
1111         }
1112         $sql =~ s/%CH%//;
1113         $sql =~ s/%DATE%//;
1114         $sql =~ s/%KEY%//;
1115         $sql =~ s/%CATEGORY%//;
1116
1117         $ary_ref = $dbh->selectall_arrayref( $sql );
1118         foreach my $prg ( @{ $ary_ref } ) {
1119                 my @date = $prg->[2] =~ /(.{4})(.{2})(.{2})(.{2})(.{2})(.{2})/;
1120
1121                 $date = $date[2];
1122                 if ( $date != $prev ) {
1123                         my $date = DateTime->new(
1124                                 year => $date[0], month  => $date[1], day    => $date[2], 
1125                                 locale => 'ja_JP'
1126                         );
1127
1128                         my $dn = $date->day_name;
1129                         #utf8::encode( $dn );
1130                         $HTML .= qq {--------$date[1]/$date[2]($dn)--------<br>\n};
1131                 }
1132                 $HTML .= qq {$date[1]/$date[2] $date[3]:$date[4] };
1133                 $HTML .= qq {$prg->[1] } if ( !$chtxt );
1134                 $HTML .= qq {<a href="rectool.pl?mode=confirm&amp;mode_sub=reserve&amp;chtxt=$prg->[0]&amp;start=$prg->[2]&amp;stop=$prg->[3]">$prg->[4]</a><br>\n};
1135                 $prev = $date;
1136         }
1137 }
1138
1139 ################ mode=list ################
1140
1141 if ( $mode eq 'list' ) {
1142         $HTML =~ s/%HTML_TITLE_OPT%/ - List/;
1143         $HTML .= qq {<div>\n};
1144
1145         $script = <<EOM;
1146                 <link rel="stylesheet" type="text/css" href="http://extjs-public.googlecode.com/svn/tags/extjs-3.4.0/release/resources/css/ext-all.css" />
1147                 <script type="text/javascript" src="http://extjs-public.googlecode.com/svn/tags/extjs-3.4.0/release/adapter/ext/ext-base.js"></script>
1148                 <script type="text/javascript" src="http://extjs-public.googlecode.com/svn/tags/extjs-3.4.0/release/ext-all.js"></script>
1149                 <style type="text/css">
1150                         .x-tip-body { font-size: 16px; }
1151                 </style>
1152                 <script>
1153                 Ext.onReady(function() {
1154                   Ext.select('.ffmpeg').on('contextmenu', function(eventObj, elRef) {
1155                     var win = new Ext.Window({
1156                       title: 'FFmpeg info', 
1157                       //autoShow: true, 
1158                       autoLoad: "rectool.pl?mode=list&mode_sub=ffmpeg&path=" + Ext.Element(elRef).getAttribute("path") + 
1159                         "&pathtype=" + Ext.Element(elRef).getAttribute("pathtype"), 
1160                     });
1161                     win.show();
1162                   }, null, {stopEvent:true});
1163 /*
1164                   Ext.select( '.ffmpeg' , true ).each(function (elem) {
1165                     // elem.dom.textContent
1166                     var tooltip = new Ext.ToolTip({
1167                       target: elem,
1168                       width: 400,
1169                       autoLoad: {url: "rectool.pl?mode=list&mode_sub=ffmpeg&path=" + elem.getAttribute("path")},
1170                       autoHide: false,
1171                       closable: true,
1172                       draggable: true, 
1173                       title: 'FFmpeg info',
1174                     });
1175                   });
1176 */
1177                 });
1178                 </script>
1179 EOM
1180         $script =~ s/^\t{2}//gm;
1181         $HTML =~ s/%SCRIPT%/$script/;
1182
1183         my $recording = $cfg->param( 'path.recpath' );
1184         my $movedest  = $cfg->param( 'path.ts_movepath' );
1185         my $recorded  = $cfg->param( 'path.recorded' );
1186
1187         if ( $mode_sub eq 'log' ) {
1188                 my $title = $params{ 'title' };
1189                 my $log = read_file( "$recording/$title.log" ) if ( -e "$recording/$title.log" );
1190                 utf8::decode( $log );
1191                 $HTML .= '<pre>'.$log."</pre>\n";
1192                 goto end;
1193         }
1194         if ( $mode_sub eq 'logzip' ) {
1195                 my $title = $params{ 'title' };
1196                 my $zip = Archive::Zip->new();
1197                 my $logzip;
1198                 die 'read error' unless $zip->read("$recording/$title.log.zip") == AZ_OK;
1199                 my @members = $zip->members();
1200                 foreach (@members) {
1201                         $logzip .= $_->fileName() . "\n";
1202                         my @lines = split /\n|\r/, $zip->contents( $_->fileName() );
1203                         my %count;
1204                         @lines = grep {!$count{$_}++} @lines;
1205                         $logzip .= join "\n", @lines;
1206                         $logzip .= "\n<hr>\n";
1207                 }
1208
1209                 utf8::decode( $logzip );
1210                 $HTML .= '<pre>'.$logzip."</pre>\n";
1211                 goto end;
1212         }
1213         if ( $mode_sub eq 'ffmpeg' ) {
1214                 my $path = $params{ 'path' };
1215                 my $pathtype = $params{ 'pathtype' };
1216                 my $pathdir;
1217                 $pathdir = $recording if ( $pathtype eq 'ing');
1218                 $pathdir = $recorded  if ( $pathtype eq 'ed' );
1219                 $pathdir = $movedest  if ( $pathtype eq 'dst');
1220                 # mediainfo (not working)
1221                 # ffprobe
1222                 # FIXME: sanitize
1223                 my $ffmpeg = `ffmpeg -i "$pathdir/$path" 2>&1` if ( -f "$pathdir/$path" );
1224                 utf8::decode($ffmpeg);
1225                 $ffmpeg = join "<br>\n", grep /Duration|Stream/, split /\n/, $ffmpeg;
1226                 $HTML = $ffmpeg;
1227                 goto end;
1228         }
1229         if ( !$mode_sub ) {
1230                 $HTML .= qq {<a href="rectool.pl?mode=list&amp;mode_sub=new">録画中のみ</a>\n};
1231                 $HTML .= qq {<a href="rectool.pl?mode=list&amp;mode_sub=old">録画後のみ</a>\n<br>\n};
1232         }
1233         if ( !$mode_sub || $mode_sub eq 'new' ) {
1234                 $HTML .= "録画中のファイル一覧<br>\n";
1235                 &list( $recording );
1236         }
1237         if ( !$mode_sub ) {
1238                 $HTML .= "<br>\n";
1239         }
1240         if ( !$mode_sub || $mode_sub eq 'old' ) {
1241                 $HTML .= "録画後のファイル一覧<br>\n";
1242                 &simple_list( $movedest );
1243                 &simple_list( $recorded );
1244         }
1245
1246         sub list {
1247                 local $path = shift;
1248                 local %list = ();
1249                 my @exp = ( 'log', 'log.zip', 'ts.b25', 'ts.tsmix', 'ts', 'ts.log', 
1250                         'aac', 'srt', 'm2v', 'wav', '264', 'mp4', 'mkv' );
1251                 for ( 0..$#exp ) {
1252                         $exp{$exp[$_]} = $_;
1253                 }
1254                 my $exp_count = scalar keys %exp;
1255
1256                 &get_file_list_wrapper( $path, \&wanted );
1257
1258                 my $help;
1259                 foreach my $name ( sort { $exp{$a} <=> $exp{$b} } keys %exp ) {
1260                         $help .= $exp{$name} + 1 . " = $name / ";
1261                 }
1262                 $HTML .= $help;
1263                 $help  = qq {<tr style="background-color: #87CEEB"><td>$help\n</td>\n};
1264                 $help .= qq {<td>$_</td>\n} for ( 1..$exp_count );
1265
1266                 $HTML .= qq {<br>\n○ = 完了 / ● = 書き込み中 / ◆ = ファイルサイズ異常<br>\n};
1267                 $HTML .= qq {<table summary="listtable" border=1 cellspacing=0>\n<tr>\n};
1268                 $HTML .= qq {<th>タイトル</th>\n};
1269                 $HTML .= qq {<th>$_</th>\n} for ( 1..$exp_count );
1270                 $HTML .= qq {</tr>\n};
1271
1272                 my $count = 0;
1273
1274                 foreach my $title ( sort keys %list ) {
1275                         my $value = $list{$title};
1276                         my @flag = ( 0 ) x ( $exp_count );
1277                         $HTML .= qq {<tr>\n<td width="600" style="width: 600px; white-space: normal">$title</td>\n};
1278                         foreach my $exp ( keys %{$value} ) {
1279                                 if ( $exp eq 'log' ) {
1280                                         # ログへのリンクを追加
1281                                         my $title = $q->escape( $title );
1282                                         my $extra = qq {<td><a href="rectool.pl?mode=list&amp;mode_sub=log&amp;title=$title">○</a></td>\n};
1283
1284                                         $value->{$exp}->{extra} = $extra;
1285                                 }
1286                                 elsif ( $exp eq 'log.zip' ) {
1287                                         # ZIPログへのリンクを追加
1288                                         my $title = $q->escape( $title );
1289                                         my $extra = qq {<td><a href="rectool.pl?mode=list&amp;mode_sub=logzip&amp;title=$title">○</a></td>\n};
1290
1291                                         $value->{$exp}->{extra} = $extra;
1292                                 }
1293                                 elsif ( $exp eq 'mp4' ) {
1294                                         # ○などの代わりにサイズを表示
1295                                         # $value->{$exp}->{style} = $value->{$exp}->{size};
1296                                         my $size = $value->{$exp}->{size};
1297                                         my $extra = qq {<td><span class="ffmpeg" path="$title.mp4" pathtype="ing">$size</span></td>\n};
1298                                         $value->{$exp}->{extra} = $extra;
1299                                 }
1300                                 elsif ( $exp eq 'mkv' ) {
1301                                         # サムネイルへのリンクを追加
1302                                         my $title = $q->escape( $title );
1303
1304                                         my $extra = qq {<td><a title="$value->{$exp}->{size}" href="rectool.pl?mode=thumb&amp;title=$title">■</a></td>\n};
1305                                         $value->{$exp}->{extra} = $extra;
1306                                 }
1307                                 $flag[$exp{$exp}] = $value->{$exp};
1308                         }
1309                         foreach ( @flag ) {
1310                                 my $size  = $_->{size};
1311                                 my $style = $_->{style};
1312                                 my $span  =  $size ? qq {<span title="$size">$style</span>} : '<br>';
1313                                 $HTML .= $_->{extra} || qq {<td>$span</td>\n};
1314                         }
1315                         $HTML .= qq {</tr>\n};
1316                         $HTML .= $help unless ( ++$count % 20 );
1317                 }
1318                 $HTML .= qq {</table>\n};
1319
1320                 sub wanted {
1321                         my $rel = shift;
1322                         my $abs = shift;
1323
1324                         return if ( $rel =~ /Thumbs\.db/ );
1325                         return if ( $rel =~ /\.idx/ );
1326
1327                         $rel =~ s/\.temp$//;
1328                         my $regexp = join '|', keys %exp;
1329                         my ( $title, $exp ) = $rel =~ /(.*?)\.($regexp)$/;
1330                         my ( $size, $style ) = &get_size( $abs );
1331                         $rel =~ s/\.temp$//;
1332                         if ( !$title ) {
1333                                 $title = '_error_exp_'.$rel;
1334                                 $exp   = 'log';
1335                         }
1336                         if ( $title !~ /[^0-9A-F]+/ ) {
1337                                 my $tmp = pack( 'H*', $title );
1338                                 if ( !$tmp ) {
1339                                         $title = '_error_b16_'.$rel;
1340                                         $exp   = 'log';
1341                                 }
1342                                 else {
1343                                         $title = 'Base16_'.$tmp;
1344                                 }
1345                         }
1346                         $list{$title}->{$exp} = { 'style' => $style, 'size' => $size };
1347                 }
1348         }
1349
1350         sub simple_list {
1351                 require Encode;
1352
1353                 local $path = shift;
1354                 local @list = ();
1355
1356                 &get_file_list_wrapper( $path, \&simple_wanted );
1357
1358 #               @list = sort @list;
1359                 # natural sortを行う
1360                         #@list = map( Encode::decode_utf8( $_ ), @list );
1361                         @list = nsort @list;
1362                         #@list = map( Encode::encode_utf8( $_ ), @list );
1363
1364                 foreach ( @list ) {
1365                         $HTML .= "$_<br>\n";
1366                 }
1367
1368                 sub simple_wanted {
1369                         my $rel = shift;
1370                         my $abs = shift;
1371
1372                         my ( $size ) = &get_size( $abs );
1373                         $rel = qq {<span class="ffmpeg" path="$rel" pathtype="ed">$rel</span>};
1374                         push @list, $rel ."\t\t". $size;
1375                 }
1376         }
1377
1378         sub get_size {
1379                 my $file = shift;
1380                 my ( $size, $last ) = (stat( $file ))[7,9];
1381                 my @unim = ("B","KiB","MiB","GiB","TiB","PiB");
1382                 my $count = 0;
1383
1384                 while($size >= 1024 ){
1385                         $count++;
1386                         $size = $size / 1024;
1387                 }
1388                 $size *= 100;
1389                 $size  = int( $size );
1390                 $size /= 100;
1391                 if ( time - $last < 10 ) {
1392                         $style = '●';
1393                 }
1394                 elsif ( $size == 0 ) {
1395                         $style = '◆';
1396                 }
1397                 else {
1398                         $style = '○';
1399                 }
1400                 return ( "$size $unim[$count]", $style );
1401         }
1402 }
1403
1404 ################ mode=thumb ################
1405
1406 if ( $mode eq 'thumb' ) {
1407         my $title = $params{ 'title' };
1408         my $pos  = $params{ 'pos' };
1409         my $recording = $cfg->param( 'path.recpath' );
1410
1411         print "Content-Type: image/jpeg\n\n";
1412         exec "ffmpeg -ss 300 -i '$recording/$title.mkv' -f image2 -pix_fmt jpg -vframes 1 -s 320x240 -";
1413         exit;
1414 }
1415
1416 ################ mode=check ################
1417
1418 if ( $mode eq 'check' ) {
1419 }
1420
1421 ################ mode=bravia ################
1422
1423 if ( $mode eq 'bravia' ) {
1424         $HTML =~ s/%HTML_TITLE_OPT%/ - Bravia/;
1425         $HTML .= qq {<div>\n};
1426         $HTML .= qq {<form method="get" action="rectool.pl">\n};
1427         $HTML .= qq {<div>\n};
1428         $HTML .= qq {<table summary="bayestable" border=1 cellspacing=0>\n<tr>\n};
1429         $HTML .= qq {<th>ID</th>\n};
1430         $HTML .= qq {<th>チャンネル</th>\n};
1431         $HTML .= qq {<th>タイトル</th>\n};
1432         $HTML .= qq {<th><a href="rectool.pl?mode=bravia">開始時刻</a></th>\n};
1433         $HTML .= qq {<th>終了時刻</th>\n};
1434         $HTML .= qq {<th>録画時間</th>\n};
1435         $HTML .= qq {<th><a href="rectool.pl?mode=bravia&amp;order=point">ポイント</a></th>\n};
1436         $HTML .= qq {<th>予約</th>\n};
1437         $HTML .= qq {</tr>\n};
1438         my $order = $params{ 'order' };
1439         if ( $order ne 'point' ) {
1440                 $order = 'btime';
1441         }
1442         else {
1443                 $order = 'point DESC';
1444         }
1445         my $ary_ref = $dbh->selectall_arrayref(
1446                 "SELECT id, chtxt, title, btime, etime, point 
1447                 FROM auto_timeline_bayes 
1448                 ORDER BY $order" );
1449
1450         foreach my $line ( @{ $ary_ref } ) {
1451                 my ( $begin, $end, $diff ) = &str2readable( $line->[3], $line->[4] );
1452
1453                 $line->[1] = $chtxt_chname{$line->[1]} || $line->[1];
1454                 $HTML .= qq {<tr align="center">\n};
1455                 $HTML .= qq {<td>$line->[0]</td>\n};
1456                 $HTML .= qq {<td>$line->[1]</td>\n};
1457                 $HTML .= qq {<td>$line->[2]</td>\n};
1458                 $HTML .= qq {<td>$begin</td>\n<td>$end</td>\n<td>$diff</td>\n};
1459                 $HTML .= qq {<td>$line->[5]</td>\n};
1460                 $HTML .= qq {<td><a href="rectool.pl?mode=confirm&amp;mode_sub=reserve&amp;bayesid=$line->[0]">予約</a></td>\n};
1461                 $HTML .= qq {</tr>\n};
1462         }
1463         $HTML .= qq {</table>\n};
1464         $HTML .= qq {</div>\n};
1465         $HTML .= qq {</form>\n};
1466
1467 }
1468
1469 ################ mode=proc ################
1470
1471 if ( $mode eq 'proc' ) {
1472         $HTML =~ s/%HTML_TITLE_OPT%/ - Proposal/;
1473         $HTML .= qq {<div>\n};
1474         $HTML .= qq {<table summary="proctable" border=1 cellspacing=0>\n<tr>\n};
1475         $HTML .= qq {<th>タイプ</th>\n};
1476         $HTML .= qq {<th>タイトル</th>\n};
1477         $HTML .= qq {<th>予約</th>\n};
1478         $HTML .= qq {</tr>\n};
1479
1480         my $ary_ref = $dbh->selectall_arrayref(
1481                 "SELECT type, chtxt, title 
1482                 FROM auto_proc 
1483                 ORDER BY title " );
1484
1485         foreach my $line ( @{ $ary_ref } ) {
1486                 my $url;
1487                 $line->[3] = $q->escape( $line->[2] );
1488                 my $opt = $dbh->selectrow_array( 
1489                         "SELECT opt FROM in_timeline_log 
1490                         WHERE title = '$line->[2]' "
1491                 );
1492
1493                 if ( $line->[0] eq 'auto_suggest_dec' ) {
1494                         unless ( $dbh->selectrow_array( 
1495                                 "SELECT 1 FROM timeline 
1496                                 WHERE ( type = 'convert_b25_ts' OR type = 'convert_b25_ts_running' )
1497                                 AND title = '$line->[2]' "
1498                         ) ) {
1499                                 $url = qq {rectool.pl?mode=confirm&amp;mode_sub=proc&amp;type=$line->[0]&amp;chtxt=$line->[1]&amp;title=$line->[3]&amp;opt=$opt};
1500                         }
1501                 }
1502                 elsif ( $line->[0] eq 'auto_suggest_enc' ) {
1503                         unless ( $dbh->selectrow_array( 
1504                                 "SELECT 1 FROM timeline 
1505                                 WHERE ( type = 'convert_ts_mp4' OR type = 'convert_ts_mp4_running' ) 
1506                                 AND title = '$line->[2]' "
1507                         ) ) {
1508                                 $url = qq {rectool.pl?mode=confirm&amp;mode_sub=proc&amp;type=$line->[0]&amp;chtxt=$line->[1]&amp;title=$line->[3]&amp;opt=$opt};
1509                         }
1510                 }
1511                 else {
1512                         unless ( $dbh->selectrow_array( 
1513                                 "SELECT 1 FROM timeline 
1514                                 WHERE ( type LIKE 'convert_avi%' OR type = 'convert_mkv' ) 
1515                                 AND title = '$line->[2]' "
1516                         ) ) {
1517                                 $url = qq {rectool.pl?mode=confirm&amp;mode_sub=proc&amp;type=$line->[0]&amp;chtxt=$line->[1]&amp;title=$line->[3]};
1518                         }
1519                 }
1520                 if ( $url ) { 
1521                         $href = qq {<a href="$url">予約</a>};
1522                 }
1523                 else {
1524                         $href = q {予約済};
1525                 }
1526
1527                 my $color = $color{$type_suggest{$line->[0]}} ? $color{$type_suggest{$line->[0]}} : '';
1528                 $line->[0] = $type{$line->[0]} ? $type{$line->[0]} : $line->[0];
1529                 $line->[0] = qq {<span style="color: $color">$line->[0]</span>} if ( $color );
1530                 $HTML .= qq {<tr align="center">\n};
1531                 $HTML .= qq {<td>$line->[0]</td>\n};
1532                 $HTML .= qq {<td align="left">$line->[2]</td>\n};
1533                 $HTML .= qq {<td>$href</td>\n};
1534                 $HTML .= qq {</tr>\n};
1535         }
1536
1537         $HTML .= qq {</table>\n};
1538 }
1539
1540 ################ mode=jbk ################
1541
1542 if ( $mode eq 'jbk' ) {
1543         $HTML =~ s/%HTML_TITLE_OPT%/ - JBK/;
1544         $HTML .= qq {<div>\n};
1545
1546         if ( $mode_sub eq 'add' ) {
1547                 my $keyword = $params{ 'keyword' };
1548                 utf8::decode( $keyword );
1549                 $HTML .= "キーワード「$keyword」を追加しました。<br>\n";
1550                 $dbh->do( 
1551                         "INSERT INTO in_auto_jbk_key ( keyword ) 
1552                         VALUES ( '$keyword' )" 
1553                 );
1554         }
1555         elsif ( $mode_sub eq 'del' ) {
1556                 my $id = $params{ 'id' };
1557                 my $keyword = $dbh->selectrow_array( 
1558                         "SELECT keyword FROM in_auto_jbk_key 
1559                         WHERE id = '$id' " );
1560                 $HTML .= "キーワード「$keyword」を削除しました。<br>\n";
1561                 $dbh->do( 
1562                         "DELETE FROM in_auto_jbk_key WHERE id = '$id'" 
1563                 );
1564         }
1565         elsif ( $mode_sub eq 'on' ) {
1566                 my $id = $params{ 'id' };
1567                 $HTML .= "キーワード「$keyword」を自動録画対象にしました。<br>\n";
1568                 $dbh->do( 
1569                         "UPDATE in_auto_jbk_key SET auto = 1 WHERE id = '$id'" 
1570                 );
1571         }
1572         elsif ( $mode_sub eq 'off' ) {
1573                 my $id = $params{ 'id' };
1574                 $HTML .= "キーワード「$keyword」を自動録画対象から外しました。<br>\n";
1575                 $dbh->do( 
1576                         "UPDATE in_auto_jbk_key SET auto = 0 WHERE id = '$id'" 
1577                 );
1578         }
1579
1580         $HTML .= qq {<table summary="jbktable" border=1 cellspacing=0>\n<tr>\n};
1581         $HTML .= qq {<th>ID</th>\n};
1582         $HTML .= qq {<th>キーワード</th>\n};
1583         $HTML .= qq {<th>自動録画</th>\n};
1584         $HTML .= qq {<th>切り替え</th>\n};
1585         $HTML .= qq {<th>録画オプション</th>\n};
1586         $HTML .= qq {<th>削除</th>\n};
1587         $HTML .= qq {</tr>\n};
1588
1589         my $ary_ref = $dbh->selectall_arrayref(
1590                 "SELECT id, keyword, auto, opt 
1591                 FROM in_auto_jbk_key
1592                 ORDER BY id " );
1593
1594         foreach my $line ( @{ $ary_ref } ) {
1595                 my $delurl = "rectool.pl?mode=jbk&amp;mode_sub=del&amp;id=$line->[0]";
1596                 my $auto = $line->[2] ? 'on' : 'off';
1597                 my $oppo = $line->[2] ? 'off' : 'on';
1598                 my $oppourl = "rectool.pl?mode=jbk&amp;mode_sub=$oppo&amp;id=$line->[0]";
1599                 $oppo .= "にする";
1600
1601                 $HTML .= qq {<tr align="center">\n};
1602                 $HTML .= qq {<td>$line->[0]</td>\n};
1603                 $HTML .= qq {<td>$line->[1]</td>\n};
1604                 $HTML .= qq {<td>$auto</td>\n};
1605                 $HTML .= qq {<td><a href="$oppourl">$oppo</a></td>\n};
1606                 $HTML .= qq {<td>$line->[3]</a></td>\n};
1607                 $HTML .= qq {<td><a href="$delurl">削除</a></td>\n};
1608                 $HTML .= qq {</tr>\n};
1609         }
1610
1611         $HTML .= qq {</table>\n};
1612
1613         $HTML .= qq {<form method="get" action="rectool.pl">\n};
1614         $HTML .= qq {<div>\n};
1615         $HTML .= qq {<input type="hidden" name="mode" value="jbk">\n};
1616         $HTML .= qq {<input type="hidden" name="mode_sub" value="add">\n};
1617         $HTML .= qq {<input name="keyword" type="text">\n};
1618         $HTML .= qq {<input type="submit" value="追加">\n</div>\n</form>\n<br>\n};
1619
1620         $HTML .= qq {<table summary="jbkrestable" border=1 cellspacing=0>\n<tr>\n};
1621         $HTML .= qq {<th>ID</th>\n};
1622         $HTML .= qq {<th>チャンネル</th>\n};
1623         $HTML .= qq {<th>タイトル</th>\n};
1624         $HTML .= qq {<th>開始時刻</th>\n};
1625         $HTML .= qq {<th>終了時刻</th>\n};
1626         $HTML .= qq {<th>録画時間</th>\n};
1627         $HTML .= qq {<th>予約</th>\n};
1628         $HTML .= qq {</tr>\n};
1629
1630         $ary_ref = $dbh->selectall_arrayref(
1631                 "SELECT id, auto_timeline_keyword.chtxt, epg_ch.chname, title, btime, etime 
1632                 FROM auto_timeline_keyword 
1633                 INNER JOIN epg_ch ON auto_timeline_keyword.chtxt = epg_ch.chtxt 
1634                 ORDER BY btime" 
1635                 , {Slice=>{}} );
1636
1637         foreach my $line ( @{ $ary_ref } ) {
1638                 my ( $begin, $end, $diff ) = &str2readable( $line->{btime}, $line->{etime} );
1639                 $line->{btime} =~ s/(.{4})-(.{2})-(.{2}) (.{2}):(.{2}):(.{2})/$1$2$3$4$5$6/;
1640                 $line->{etime} =~ s/(.{4})-(.{2})-(.{2}) (.{2}):(.{2}):(.{2})/$1$2$3$4$5$6/;
1641                 my $url = qq "rectool.pl?mode=confirm&amp;mode_sub=reserve&amp;chtxt=$line->{chtxt}&amp;start=$line->{btime}&amp;stop=$line->{etime}";
1642
1643                 $HTML .= qq {<tr align="center">\n};
1644                 $HTML .= qq {<td>$line->{id}</td>\n};
1645                 $HTML .= qq {<td>$line->{chname}</td>\n};
1646                 $HTML .= qq {<td>$line->{title}</td>\n};
1647                 $HTML .= qq {<td>$begin</td>\n};
1648                 $HTML .= qq {<td>$end</td>\n};
1649                 $HTML .= qq {<td>$diff</td>\n};
1650                 $HTML .= qq {<td><a href="$url">予約</a></td>\n};
1651                 $HTML .= qq {</tr>\n};
1652         }
1653
1654         $HTML .= qq {</table>\n};
1655
1656 }
1657
1658 ################ mode=recognize ################
1659
1660 if ( $mode eq 'recognize' ) {
1661         $HTML =~ s/%HTML_TITLE_OPT%/ - Recognizer/;
1662
1663         my $text  = $params{ 'text' };
1664         utf8::decode( $text );
1665         $chtxt = $params{ 'chtxt' };
1666         my $title = $params{ 'title' };
1667         utf8::decode( $title );
1668
1669         $HTML .= qq {<div>\n};
1670         $HTML .= qq {与えられた文字列のうち、番組の放送時刻と思われる文字列を認識します。<br>\n};
1671         $HTML .= qq {番組表が取得できない一週間以上先の予約ができます。<br>\n};
1672         $HTML .= qq {<form method="post" action="rectool.pl">\n};
1673         $HTML .= qq {<div>\n};
1674         &draw_form_channel( 'nonone' );
1675         $HTML .= qq {<input type="text" name="title" value="$title">\n};
1676         $HTML .= qq {<br>\n};
1677         $HTML .= qq {<input type="hidden" name="mode" value="recognize">\n};
1678         $HTML .= qq {<textarea name="text" cols=40 rows=4>\n$text</textarea>\n};
1679         $HTML .= qq {<input type="submit" value="実行">\n</div>\n</form>\n};
1680
1681         my $ch_list = join '|', grep /.+/, values %chtxt_0_chname;
1682         my %ch_reverse = reverse %chtxt_0_chname;
1683
1684         if ( $text ) {
1685                 my ( $year, $month, $day );
1686                 my ( $bhour, $bminute, $ehour, $eminute );
1687                 my $next_day = 0;
1688                 foreach ( split /\n/, $text ) {
1689                         my @bdate = /(\d{4}).(\d{1,2}).(\d{1,2})/;
1690                         s/(\d{4}).(\d{2}).(\d{2})//;
1691                         my @btime = /(\d{1,2})[::](\d{1,2})/;
1692                         s/(\d{1,2})[::](\d{2})//;
1693                         my @etime = /(\d{1,2})[::](\d{1,2})/;
1694                         s/(\d{1,2})[::](\d{2})//;
1695                         s/\(.*\)//;
1696                         if ( !@bdate ) {
1697                                 $bdate[0] = Time::Piece->localtime->year;
1698                                 ( $bdate[1], $bdate[2] ) = /(\d{1,2})月(\d{1,2})日/;
1699                                 s/(\d{1,2})月(\d{1,2})日//;
1700                         }
1701                         next if (!( @bdate || @btime ));
1702                         ( $year,  $month, $day ) = @bdate if ( $bdate[0] && $bdate[1] && $bdate[2] );
1703                         ( $bhour, $bminute )     = @btime if ( defined $btime[0] && defined $btime[1] );
1704                         ( $ehour, $eminute )     = @etime if ( defined $etime[0] && defined $etime[1] );
1705                         $next_day = 1 if ( /深夜/ );
1706                         my ( $ch ) = /($ch_list)/;
1707                         my $chtxt = $ch_reverse{$ch} if ( $ch && $ch_reverse{$ch} );
1708                         s/($ch_list)//;
1709
1710                         if ( $year && $month && $day && defined $bhour && defined $bminute ) {
1711                                 my $tp  = Time::Piece->strptime( "$year-$month-$day $bhour:$bminute", '%Y-%m-%d %H:%M' );
1712                                 my $etp = Time::Piece->strptime( "$year-$month-$day $ehour:$eminute", '%Y-%m-%d %H:%M' ) if ( defined $ehour && defined $eminute );
1713                                 $tp += ONE_DAY if ( $next_day );
1714                                 my $start = $tp->strftime( '%Y%m%d%H%M%S' );
1715                                 my $stop  = defined $etp ? 
1716                                         $etp->strftime( '%Y%m%d%H%M%S' ) :
1717                                         ( $tp + ONE_MINUTE * 30 )->strftime( '%Y%m%d%H%M%S' );
1718                                 $title = $_ if ( !$title );
1719                                 my $url = qq "rectool.pl?mode=confirm&amp;mode_sub=reserve&amp;chtxt=$chtxt&amp;start=$start&amp;stop=$stop&amp;title=$title";
1720                                 $HTML .= qq {認識結果:$year-$month-$day $bhour:$bminute -> $ehour:$eminute 残り:$_<a href="$url">リンク</a> <br>\n};
1721                         }
1722                 }
1723         }
1724 }
1725
1726 ################ mode=expert ################
1727
1728 if ( $mode eq 'expert' ) {
1729         require List::Compare;
1730
1731         my $ary_ref;
1732
1733         $HTML =~ s/%HTML_TITLE_OPT%/ - Expert/;
1734         $HTML .= qq {<div>\n};
1735
1736         if ( $mode_sub eq 'reget' ) {
1737                 my $bctype = $params{ 'bctype' };
1738                 my ( $chtxt, $chname ) = $dbh->selectrow_array( 
1739                         "SELECT chtxt, chname FROM epg_ch 
1740                         WHERE bctype = '$bctype' " );
1741                 $HTML .= "Update for $chname ( chtxt: $chtxt ) has been reserved.<br>\n";
1742                 $dbh->do( "UPDATE epg_ch SET status = '2' WHERE chtxt = '$chtxt' " );
1743                 goto end;
1744         }
1745
1746
1747         my @ary = $dbh->selectrow_array(
1748                 "SELECT auto_jbk, auto_bayes, auto_del_tmp, auto_opt 
1749                 FROM in_settings " );
1750         my $opt = pop @ary;
1751         @ary = map( $_ ? 'checked' : '', @ary );
1752
1753         $HTML .= qq {内部オプションの変更\n<br>};
1754         $HTML .= qq {<form method="get" action="rectool.pl">\n};
1755         $HTML .= qq {<div>\n};
1756         $HTML .= qq {<input type="hidden" name="mode"     value="change">\n};
1757         $HTML .= qq {<input type="hidden" name="mode_sub" value="setting">\n};
1758         $HTML .= qq {<input type="checkbox" name="jbk"     value="1" $ary[0]>自動地引\n};
1759         $HTML .= qq {<input type="checkbox" name="bayes"   value="1" $ary[1]>自動ベイズ\n};
1760         $HTML .= qq {<input type="checkbox" name="del_tmp" value="1" $ary[2]>自動一時ファイル削除\n};
1761         $HTML .= qq {自動オプション:<input type="text" name="opt" value="$opt">\n};
1762         $HTML .= qq {<input type="submit" value="保存">\n</div>\n</form>\n};
1763
1764
1765         $HTML .= qq {<hr>\n番組表のカテゴリ一覧と内蔵のカテゴリ一覧の合致を確認中...\n};
1766         $ary_ref = $dbh->selectcol_arrayref(
1767                 "SELECT DISTINCT category FROM epg_timeline"
1768         );
1769         my @category = map {$_->{name}} sort values %category;
1770         if ( List::Compare->new( $ary_ref, \@category )->get_symdiff ) {
1771                 $HTML .= qq {一致しません<br>\n};
1772                 $HTML .= qq {番組表:@{$ary_ref}<br>\n内蔵:@category<br>\n};
1773         }
1774         else {
1775                 $HTML .= qq {一致しました<br>\n};
1776         }
1777
1778
1779         @ary = $dbh->selectrow_array( "SELECT terec, bscsrec, b252ts, ts2avi FROM in_status" );
1780         $HTML .= qq {<hr>\n地上波録画数:$ary[0]\n衛星波録画数:$ary[1]\n解読数:$ary[2]\n縁故数:$ary[3]\n<br>\n};
1781         $HTML .= qq {<form method="get" action="rectool.pl">\n};
1782         $HTML .= qq {<div>\n};
1783         $HTML .= qq {<input type="hidden" name="mode"     value="change">\n};
1784         $HTML .= qq {<input type="hidden" name="mode_sub" value="fixstatus">\n};
1785         $HTML .= qq {<input type="submit" name="terec"   value="地上波録画数をリセット">\n};
1786         $HTML .= qq {<input type="submit" name="bscsrec" value="衛星波録画数をリセット">\n};
1787         $HTML .= qq {<input type="submit" name="b252ts"  value="解読数をリセット">\n};
1788         $HTML .= qq {<input type="submit" name="ts2avi"  value="縁故数をリセット">\n</div>\n</form>\n};
1789
1790
1791         $HTML .= qq {<hr>\nRec10 バージョン:$rec10_version\nrectool バージョン:$rectool_version\n<br>\n};
1792
1793
1794         $HTML .= qq {<hr>\n番組表の欠落<br>\n};
1795         $ary_ref = $dbh->selectall_arrayref( "SELECT chname, chtxt FROM epg_ch" );
1796         foreach my $line ( @{$ary_ref} ) {
1797                 my $ary_ref = $dbh->selectall_arrayref( 
1798                         "SELECT start, stop, title FROM epg_timeline WHERE channel = '$line->[1]' ORDER BY start" 
1799                 );
1800                 my $error;
1801                 my @program_old = ( '', $ary_ref->[0]->[0] );
1802                 my $program_old = \@program_old;
1803
1804                 foreach my $program_new ( @{$ary_ref} ) {
1805                         if ( $program_old->[1] ne $program_new->[0] && 
1806                                 $program_old->[2] !~ /クロ?ジング|クロージング|エンディング|休止|ミッドナイト|ending/ && 
1807                                 $program_new->[2] !~ /オープニング|ウィークリー・インフォメーション|モーニング|opening/ && 
1808                                 ( str2datetime( $program_new->[0] ) - str2datetime( $program_old->[1] ) )->delta_minutes > 30 ) {
1809                                 $program_old->[1] =~ s/(.{4})(.{2})(.{2})(.{2})(.{2})(.{2})/$1-$2-$3 $4:$5:$6/;
1810                                 $program_new->[0] =~ s/(.{4})(.{2})(.{2})(.{2})(.{2})(.{2})/$1-$2-$3 $4:$5:$6/;
1811                                 $error .= qq{    $program_old->[2]    $program_old->[1]\n    ->  $program_new->[2]    $program_new->[0]\n};
1812                         }
1813                         $program_old = $program_new;
1814                 }
1815                 $HTML .= qq {<pre>\n$line->[0]\n$error</pre>\n} if ( $error );
1816                 }
1817
1818
1819         $ary_ref = $dbh->selectall_arrayref( 
1820                 "SELECT chname, chtxt, bctype, ch, csch, updatetime, status, visible 
1821                 FROM epg_ch 
1822                 ORDER BY bctype " );
1823         $HTML .= qq {<hr>\n番組表の更新状況<br>\n};
1824         $HTML .= qq {<table summary="channeltable" border=1 cellspacing=0>\n<tr>\n};
1825         $HTML .= qq {<th>チャンネル名</th>\n};
1826         $HTML .= qq {<th>chtxt</th>\n};
1827         $HTML .= qq {<th>bctype</th>\n};
1828         $HTML .= qq {<th>ch</th>\n};
1829         $HTML .= qq {<th>csch</th>\n};
1830         $HTML .= qq {<th>最終更新時刻</th>\n};
1831         $HTML .= qq {<th>状態</th>\n};
1832         $HTML .= qq {<th>表示</th>\n};
1833         $HTML .= qq {</tr>\n};
1834         foreach my $status ( @{$ary_ref} ) {
1835                 $HTML .= qq {<tr>\n};
1836                 $HTML .= qq {<td>$status->[0]</td>\n<td>$status->[1]</td>\n<td>$status->[2]</td>\n<td>$status->[3]</td>\n};
1837                 $HTML .= qq {<td>$status->[4]</td>\n<td>$status->[5]</td>\n<td>$status->[6]</td>\n<td>$status->[7]</td>\n};
1838                 $HTML .= qq {</tr>\n};
1839         }
1840         $HTML .= qq {</table>\n};
1841
1842         $HTML .= qq {<form method="get" action="rectool.pl">\n};
1843         $HTML .= qq {<div>\n};
1844         $HTML .= qq {番組表を再取得する\n};
1845         $HTML .= qq {<input type="hidden" name="mode" value="expert">\n};
1846         $HTML .= qq {<input type="hidden" name="mode_sub" value="reget">\n};
1847         $HTML .= qq {<select name="bctype">\n};
1848         $ary_ref = $dbh->selectall_arrayref(
1849                 "SELECT chname, bctype 
1850                 FROM epg_ch WHERE bctype NOT LIKE '_s%' "
1851         );
1852         foreach my $line ( @{$ary_ref} ) {
1853                 $HTML .= qq {<option value="$line->[1]">$line->[0]</option>\n};
1854         }
1855         $HTML .= qq {<option value="bs">BS</option>\n};
1856         $HTML .= qq {<option value="cs1">CS1</option>\n};
1857         $HTML .= qq {<option value="cs2">CS2</option>\n};
1858         $HTML .= qq {</select>\n};
1859         $HTML .= qq {<input type="submit" value="実行">\n</div>\n</form>\n};
1860
1861
1862
1863         $ary_ref = $dbh->selectall_arrayref(
1864                 "SELECT id, type, chtxt, title, btime, etime, opt, deltaday, deltatime 
1865                 FROM timeline 
1866                 ORDER BY id ");
1867         $HTML .= qq {<hr>\n予約表<br>\n};
1868         $HTML .= qq {<table summary="rectimetable" border=1 cellspacing=0>\n<tr>\n};
1869         $HTML .= qq {<th>ID</th>\n};
1870         $HTML .= qq {<th>type</th>\n};
1871         $HTML .= qq {<th>chtxt</th>\n};
1872         $HTML .= qq {<th>title</th>\n};
1873         $HTML .= qq {<th>btime</th>\n};
1874         $HTML .= qq {<th>etime</th>\n};
1875         $HTML .= qq {<th>opt</th>\n};
1876         $HTML .= qq {<th>deltaday</th>\n};
1877         $HTML .= qq {<th>deltatime</th>\n};
1878         $HTML .= qq {</tr>\n};
1879         foreach my $status ( @{$ary_ref} ) {
1880                 $HTML .= qq {<tr>\n};
1881                 $HTML .= qq {<td>$status->[0]</td>\n<td>$status->[1]</td>\n<td>$status->[2]</td>\n<td>$status->[3]</td>\n};
1882                 $HTML .= qq {<td>$status->[4]</td>\n<td>$status->[5]</td>\n<td>$status->[6]</td>\n<td>$status->[7]</td>\n};
1883                 $HTML .= qq {<td>$status->[8]</td>\n};
1884                 $HTML .= qq {</tr>\n};
1885         }
1886         $HTML .= qq {</table>\n};
1887 }
1888
1889 ################ mode=log ################
1890
1891 if ( $mode eq 'log' ) {
1892         $HTML =~ s/%HTML_TITLE_OPT%/ - Log/;
1893
1894         $HTML .= qq {<div>\n};
1895         $HTML .= qq {<table summary="reclogtable" border=1 cellspacing=0>\n<tr>\n};
1896         $HTML .= qq {<th>ID</th>\n};
1897         $HTML .= qq {<th>chtxt</th>\n};
1898         $HTML .= qq {<th>title</th>\n};
1899         $HTML .= qq {<th>btime</th>\n};
1900         $HTML .= qq {<th>etime</th>\n};
1901         $HTML .= qq {<th>opt</th>\n};
1902         $HTML .= qq {<th>exp</th>\n};
1903         $HTML .= qq {<th>longexp</th>\n};
1904         $HTML .= qq {<th>category</th>\n};
1905         $HTML .= qq {</tr>\n};
1906         $ary_ref = $dbh->selectall_arrayref(
1907                 "SELECT id, chtxt, title, btime, etime, opt, exp, longexp, category 
1908                 FROM in_timeline_log "
1909         );
1910         foreach my $line ( @{$ary_ref} ) {
1911                 $HTML .= qq {<tr>\n};
1912                 $HTML .= qq {<td>$line->[0]</td>\n<td>$line->[1]</td>\n<td>$line->[2]</td>\n<td>$line->[3]</td>\n};
1913                 $HTML .= qq {<td>$line->[4]</td>\n<td>$line->[5]</td>\n<td>$line->[6]</td>\n<td>$line->[7]</td>\n};
1914                 $HTML .= qq {<td>$line->[8]</td>\n};
1915                 $HTML .= qq {</tr>\n};
1916         }
1917         $HTML .= qq {</table>\n};
1918 }
1919
1920 ################ mode=help ################
1921
1922 if ( $mode eq 'help' ) {
1923         $HTML =~ s/%HTML_TITLE_OPT%/ - Help/;
1924         $HTML =~ s|%REFRESH%|<meta http-equiv="refresh" content="300">|;
1925         $HTML .= qq {<div>\n};
1926         $HTML .= qq {ヘルプ\n};
1927 }
1928
1929 ################ mode=test ################
1930
1931 if ( $mode eq 'test' ) {
1932         $HTML =~ s/%HTML_TITLE_OPT%/ - Test/;
1933         $HTML =~ s|%REFRESH%|<meta http-equiv="refresh" content="300">|;
1934         $HTML .= qq {<div>\n};
1935
1936         require Data::Dumper;
1937         $tmp = read_file( '/etc/rec10.conf' );
1938         $tmp =~ s/\n/<br>\n/gs;
1939         $HTML .= $tmp;
1940
1941         # $HTML .= Dumper( $ary_ref );
1942 }
1943
1944 ################ mode nasi ################
1945
1946 if ( !$mode ) {
1947         &draw_form();
1948         $HTML =~ s/%HTML_TITLE_OPT%/ - Top/;
1949         $HTML .= qq {Welcome to Rec10!<br>\n};
1950         goto end;
1951 }
1952
1953
1954 end:
1955 #<div style="float: right">
1956 $HTML .= <<EOM;
1957 </div>
1958 </body>
1959 </html>
1960 EOM
1961
1962 #<div align="center">
1963 #$HTML_ADV = $HTML_ADV_IMG . $HTML_ADV_TEXT if ( !$HTML_ADV );
1964 my $HTML_ADV = '';
1965 $HTML_HEADER = qq {<div style="text-align: center">\n$HTML_ADV\n</div>\n};
1966
1967 &draw_menu();
1968 $HTML =~ s/%HTML_TITLE_OPT%//;
1969 $HTML =~ s/%REFRESH%//;
1970 $HTML =~ s/%SCRIPT%//;
1971 $HTML =~ s/%CSS%//;
1972 $HTML =~ s/%HTML_HEADER%/$HTML_HEADER/;
1973
1974 utf8::encode( $HTML );
1975 print $HTTP_HEADER;
1976 print $HTML;
1977 exit;
1978
1979 sub draw_menu {
1980         $hires = Time::HiRes::time() - $hires;
1981         $last_modified = localtime((stat 'rectool.pl')[9]);
1982
1983         $HTML_HEADER .= qq {<div>\n};
1984         $HTML_HEADER .= qq {<span style="float: right; font-size: 8px">Last-Modified: $last_modified<br>Time-Elapsed: $hires 秒</span>\n};
1985         $HTML_HEADER .= qq {<span style="float: left">\n};
1986         $HTML_HEADER .= qq {<a href="rectool.pl">トップ(検索)</a>\n};
1987         $HTML_HEADER .= qq {<a href="rectool.pl?mode=schedule">予約確認</a>\n};
1988         $HTML_HEADER .= qq {<a href="rectool.pl?mode=graph">予約状況(画像版)</a>\n};
1989         $HTML_HEADER .= qq {<a href="rectool.pl?mode=list">録画一覧</a>\n};
1990         $HTML_HEADER .= qq {<a href="rectool.pl?mode=bravia">おまかせ</a>\n};
1991         $HTML_HEADER .= qq {<a href="rectool.pl?mode=expert">玄人仕様</a>\n};
1992         $HTML_HEADER .= qq {<a href="rectool.pl?mode=proc">復旧支援</a>\n};
1993         $HTML_HEADER .= qq {<a href="rectool.pl?mode=jbk">地引</a>\n};
1994         $HTML_HEADER .= qq {<a href="rectool.pl?mode=log">録画履歴</a>\n};
1995         $HTML_HEADER .= qq {<a href="rectool.pl?mode=recognize">文字認識</a>\n};
1996         $HTML_HEADER .= qq {<a href="rectool.pl?mode=edit">新規予約</a>\n};
1997 #       $HTML_HEADER .= qq {<a href="../rec10web/rec10web.py">新規予約</a>\n};
1998         $HTML_HEADER .= qq {</span>\n};
1999         $HTML_HEADER .= qq {<hr style="clear: both; background-color: grey; height: 4px">\n};
2000         $HTML_HEADER .= qq {</div>\n};
2001 }
2002
2003 sub draw_form {
2004         $chname = $params{ 'chname' };
2005         $chtxt  = $params{ 'chtxt' };
2006         $key    = $params{ 'key' };
2007         utf8::decode( $key );
2008         if ( $chname ) {
2009                 $chtxt = $dbh->selectrow_array("SELECT chtxt FROM epg_ch WHERE chname = '$chname' ");
2010         }
2011
2012         $HTML .= qq {<div style="float: left">\n};
2013         $HTML .= qq {<form method="get" action="rectool.pl">\n};
2014         $HTML .= qq {<div>\n};
2015         $HTML .= qq {<input type="hidden" name="mode" value="program">\n};
2016
2017         # チャンネル指定
2018         &draw_form_channel();
2019
2020         # 日付指定
2021         $HTML .= qq {<select name="date">\n<option value="" selected>無指定</option>\n};
2022         $ary_ref = $dbh->selectcol_arrayref(
2023                 "SELECT DISTINCT SUBSTRING(start, 1, 8) FROM epg_timeline ORDER BY start"
2024         );
2025         $date_sel = $params{ 'date' };
2026         foreach my $date ( @{ $ary_ref } ) {
2027                 my @date = $date =~ /(.{4})(.{2})(.{2})/;
2028                 $date_prt = "$date[1]/$date[2]";
2029
2030                 if ( $date eq $date_sel ) {
2031                         $HTML .= qq {<option value="$date" selected>$date_prt</option>\n};
2032                 }
2033                 else {
2034                         $HTML .= qq {<option value="$date">$date_prt</option>\n};
2035                 }
2036         }
2037         $HTML .= qq {</select>\n};
2038
2039         # カテゴリ指定
2040         $HTML .= qq {<select name="category">\n<option value="" selected>無指定</option>\n};
2041         $category_sel = $params{ 'category' };
2042         foreach my $category ( keys %category ) {
2043                 if ( $category eq $category_sel ) {
2044                         $HTML .= qq {<option value="$category" selected>$category{$category}->{name}</option>\n};
2045                 }
2046                 else {
2047                         $HTML .= qq {<option value="$category">$category{$category}->{name}</option>\n};
2048                 }
2049         }
2050         $HTML .= qq {</select>\n};
2051
2052         # キーワード指定
2053         $HTML .= qq {<input name="key" type="text" value="$key" style="width:200px" accesskey="s">\n};
2054
2055         # フォーム描画
2056         $HTML .= qq {<input type="submit" value="更新" accesskey="r">\n</div>\n</form>\n};
2057 }
2058
2059 sub draw_form_channel {
2060         $HTML .= qq {<select name="chtxt">\n};
2061         $HTML .= qq {<option value="" selected>無指定</option>\n} if ( shift ne 'nonone' );
2062
2063         foreach my $key ( keys %chtxt_0_chname ) {
2064                 my $value = $chtxt_0_chname{$key};
2065                 if ( ($chtxt && $key eq $chtxt ) || ( $chname && $value eq $chname ) ) {
2066                         $HTML .= qq {<option value="$key" selected>$value</option>\n};
2067                 }
2068                 else {
2069                         $HTML .= qq {<option value="$key">$value</option>\n};
2070                 }
2071         }
2072         $HTML .= qq {</select>\n};
2073 }
2074
2075 sub draw_form_opt {
2076         my $shift = shift;
2077         my ( %selected, %checked );
2078
2079         if ( $chtxt  =~ /BS_103/ ) {
2080                 $selected{F} = 'selected';
2081         }
2082         elsif ( $chtxt  =~ /CS_239|CS_240|CS_335/ ) {
2083                 $selected{H} = 'selected';
2084         }
2085         elsif ( $chtxt =~ /BS_101|BS_102/ || $bctype =~ /cs/ ) {
2086                 $selected{W} = 'selected';
2087         }
2088         elsif ( $bctype =~ /bs|te/ ) {
2089                 $selected{H} = 'selected';
2090         }
2091         $selected{g} = 'selected';
2092         $selected{s} = 'selected';
2093         $checked{a} = $chtxt =~ /CS_331|CS_332|CS_333|CS_334|CS_335/ || $category =~ /アニメ/ ? 'checked' : '';
2094         $checked{l} = '';
2095         $checked{d} = $title =~ /\Q[二]\E|[二]|\Q(二)\E|(二)/ ? 'checked' : '';
2096         $checked{5} = $title =~ /5\.1|5.1/ ? 'checked' : '';
2097         $checked{2} = 'checked';
2098
2099         if ( $opt ) {
2100                 undef %checked;
2101                 undef %selected;
2102                 my @opt = split //, $opt;
2103                 foreach my $opt ( @opt ) {
2104                         $selected{$opt} = 'selected' if ( $opt =~ /S|L|G|H|F/ );
2105                         $checked {$opt} = 'checked'  if ( $opt =~ /a|h|l|d|2|5/ );
2106                 }
2107                 $checked{d} = $title =~ /\Q[二]\E|[二]|\Q(二)\E|(二)/ ? 'checked' : '';
2108                 $checked{5} = $title =~ /5\.1|5.1/ ? 'checked' : '';
2109         }
2110         # 画質/圧縮率ともに指定されていない場合、真ん中をselectedにする
2111         $selected{g} = 'selected' unless ( $selected{u} || $selected{i} || $selected{o} || $selected{p} );
2112         $selected{s} = 'selected' unless ( $selected{q} || $selected{w} || $selected{e} || $selected{r} );
2113
2114         $HTML .= qq {<select name="opt">\n};
2115         #$HTML .= qq {<option value="S" $selected{S}>S 720x480</option>\n};
2116         $HTML .= qq {<option value="W" $selected{W}>W 854x480</option>\n};
2117         $HTML .= qq {<option value="H" $selected{H}>H 1280x720</option>\n};
2118         $HTML .= qq {<option value="F" $selected{F}>F 1920x1080</option>\n};
2119         $HTML .= qq {<option value="I" $selected{I}>I インタレ保持</option>\n};
2120         $HTML .= qq {</select>\n};
2121
2122         $HTML .= qq {<select name="opt">\n};
2123         $HTML .= qq {<option value="u" $selected{u}>最低</option>\n};
2124         $HTML .= qq {<option value="i" $selected{i}>低</option>\n};
2125         $HTML .= qq {<option value=""  $selected{g}>画質</option>\n};
2126         $HTML .= qq {<option value="o" $selected{o}>高</option>\n};
2127         $HTML .= qq {<option value="p" $selected{p}>最高</option>\n};
2128         $HTML .= qq {</select>\n};
2129
2130         $HTML .= qq {<select name="opt">\n};
2131         $HTML .= qq {<option value="q" $selected{q}>最低</option>\n};
2132         $HTML .= qq {<option value="w" $selected{w}>低</option>\n};
2133         $HTML .= qq {<option value=""  $selected{s}>圧縮率</option>\n};
2134         $HTML .= qq {<option value="e" $selected{e}>高</option>\n};
2135         $HTML .= qq {<option value="r" $selected{r}>最高</option>\n};
2136         $HTML .= qq {</select>\n};
2137
2138         $HTML .= qq {<select name="opt">\n};
2139         $HTML .= qq {<option value=""  $selected{s}>コンテナ</option>\n};
2140         $HTML .= qq {<option value="m" $selected{e}>MKV</option>\n};
2141         $HTML .= qq {<option value="4" $selected{r}>MP4</option>\n};
2142         $HTML .= qq {</select>\n};
2143
2144         $HTML .= qq {<select name="opt">\n};
2145         $HTML .= qq {<option value=""  $selected{s}>モバイル向け</option>\n};
2146         $HTML .= qq {<option value="1" $selected{e}>QVGA</option>\n};
2147         $HTML .= qq {<option value="2" $selected{r}>WVGA</option>\n};
2148         $HTML .= qq {<option value="B" $selected{B}>Blu-ray向け</option>\n};
2149         $HTML .= qq {</select>\n};
2150
2151         $HTML .= qq {<input type="checkbox" name="opt" value="a" $checked{a}>24fps(主にアニメ)\n};
2152         $HTML .= qq {<input type="checkbox" name="opt" value="d" $checked{d}>二ヶ国語放送\n};
2153         #$HTML .= qq {<input type="checkbox" name="opt" value="2" $checked{2}>2passモード\n};
2154         $HTML .= qq {<input type="checkbox" name="opt" value="5" $checked{5}>5.1ch放送\n};
2155         $HTML .= qq {<br>\n};
2156         $HTML .= qq {<select name="opt">\n};
2157         $HTML .= qq {<option value="">移動なし</option>\n};
2158         $HTML .= qq {<option value="R">録画後移動</option>\n};
2159         $HTML .= qq {<option value="D">解読後移動</option>\n};
2160         $HTML .= qq {<option value="E">縁故後移動</option>\n};
2161         $HTML .= qq {</select>\n};
2162         $HTML .= qq {<input type="checkbox" name="opt"   value="N">ファイル名日時追加\n} if ( $shift eq 'reserve' );
2163         $HTML .= qq {<input type="checkbox" name="every" value="1">隔週録画\n}           if ( $shift eq 'reserve' );
2164 }
2165
2166 sub parse_program {
2167         $chname  = $params{ 'chname' };
2168         $chtxt   = $params{ 'chtxt' };
2169         $start   = $params{ 'start' };
2170         $stop    = $params{ 'stop' };
2171         $bayesid = $params{ 'bayesid' };
2172         $id      = $params{ 'id' };
2173
2174         if ( $chname ) {
2175                 $chtxt = $dbh->selectrow_array("SELECT chtxt FROM epg_ch WHERE chname = '$chname'");
2176         }
2177         elsif ( $chtxt && $chtxt_0_chname{$chtxt} ) {
2178                 $chname = $chtxt_0_chname{$chtxt};
2179                 ( $chtxt_sql = $chtxt ) =~ s/_0/_%/;
2180                 $bctype = $dbh->selectrow_array("SELECT bctype FROM epg_ch WHERE chtxt LIKE '$chtxt_sql'");
2181         }
2182         elsif ( $chtxt ) {
2183                 $chname = $dbh->selectrow_array("SELECT chname FROM epg_ch WHERE chtxt = '$chtxt'")
2184         }
2185         ( $title, $desc, $longdesc, $category ) = $dbh->selectrow_array(
2186                 "SELECT title, exp, longexp, category
2187                 FROM epg_timeline 
2188                 WHERE channel = '$chtxt' AND start = '$start' AND stop = '$stop' ");
2189         if ( !$bctype ) {
2190                 $bctype = $dbh->selectrow_array("SELECT bctype FROM epg_ch WHERE chtxt = '$chtxt'");
2191         }
2192
2193         if ( $bayesid ) {
2194                 ( $chtxt, $title, $begin, $end ) = $dbh->selectrow_array( 
2195                         "SELECT chtxt, title, btime, etime FROM auto_timeline_bayes WHERE id = '$bayesid' " 
2196                 );
2197                 ( $chname, $bctype ) = $dbh->selectrow_array( 
2198                         "SELECT chname, bctype FROM epg_ch WHERE chtxt = '$chtxt' " 
2199                 );
2200                 $start = str2datetime( $begin )->strftime( '%Y%m%d%H%M%S' );
2201                 $stop  = str2datetime( $end   )->strftime( '%Y%m%d%H%M%S' );
2202                 ( $desc, $longdesc, $category ) = $dbh->selectrow_array( 
2203                         "SELECT exp, longexp, category FROM epg_timeline WHERE channel = '$chtxt' AND start = '$start' AND stop = '$stop' " 
2204                 );
2205         }
2206         if ( $id ) {
2207                 ( $type, $chtxt, $title, $begin, $end, $deltaday, $deltatime, $opt, $counter ) = $dbh->selectrow_array( 
2208                         "SELECT type, chtxt, title, btime, etime, deltaday, deltatime, opt, counter 
2209                         FROM timeline WHERE id = '$id' " 
2210                 );
2211                 &chtxt_format();
2212                 ( $chname, $bctype ) = $dbh->selectrow_array( 
2213                         "SELECT chname, bctype FROM epg_ch WHERE chtxt LIKE '$chtxt_sql' " 
2214                 );
2215                 $start = str2datetime( $begin )->strftime( '%Y%m%d%H%M%S' );
2216                 $stop  = str2datetime( $end   )->strftime( '%Y%m%d%H%M%S' );
2217                 ( $desc, $longdesc, $category ) = $dbh->selectrow_array( 
2218                         "SELECT exp, longexp, category FROM epg_timeline WHERE channel = '$chtxt' AND start = '$start' AND stop = '$stop' " 
2219                 );
2220         }
2221         # set $chtxt_0, $chtxt_sql, $bctype_sql
2222         &chtxt_format();
2223         #( $chtxt_no0 ) = $chtxt   =~ /(\d+)_/;
2224         @start = $start =~ /(.{4})(.{2})(.{2})(.{2})(.{2})/;
2225         @stop  = $stop  =~ /(.{4})(.{2})(.{2})(.{2})(.{2})/;
2226         $begin = sprintf( '%04d-%02d-%02d %02d:%02d:%02d', @start, '00' );
2227         $end   = sprintf( '%04d-%02d-%02d %02d:%02d:%02d', @stop , '00' );
2228
2229         if ( $params{ 'title' } ) {
2230                 $title = $params{ 'title' };
2231                 utf8::decode( $title );
2232         }
2233         $HTML .= qq {<!-- chtxt=$chtxt chtxt_0=$chtxt_0 chtxt_sql=$chtxt_sql bctype=$bctype -->\n};
2234 }
2235
2236 sub check_error {
2237         my $is_error;
2238         my $is_same = $dbh->selectrow_array( 
2239                 "SELECT COUNT(*) FROM timeline WHERE chtxt = '$chtxt' AND btime = '$begin' AND etime = '$end'" 
2240         );
2241         my @overlap = &get_overlap();
2242
2243         if ( $is_same ) {
2244                 $HTML .= "同一の番組が既に存在します。<br>\n";
2245                 $is_error = 1;
2246         }
2247         elsif ( $overlap[0] >= 2 ) {
2248                 $HTML .= "時間が被る番組が既に2個存在します。<br>\n";
2249                 $HTML .= $overlap[1];
2250                 $is_error = 2;
2251         }
2252         else {
2253                 $is_error = 0;
2254         }
2255         return $is_error;
2256 }
2257
2258 sub get_overlap {
2259         require List::Util;
2260
2261         my $ary_ref = $dbh->selectall_arrayref(
2262                 "SELECT btime, etime, title
2263                 FROM timeline 
2264                 INNER JOIN epg_ch ON timeline.chtxt = epg_ch.chtxt 
2265                 WHERE bctype LIKE '$bctype_sql' AND type IN $type_user_made 
2266                 AND btime < '$end' 
2267                 AND etime > '$begin' 
2268                 "
2269         );
2270
2271         my %overlap;
2272         my $overlap = $max = 0;
2273         my $str;
2274         foreach my $prg ( @{ $ary_ref } ) {
2275                 $str .= "$prg->[0] ? $prg->[1] : $prg->[2]<br>\n";
2276                 $overlap{$prg->[0]} += 1;
2277                 $overlap{$prg->[1]} -= 1;
2278         }
2279         foreach my $key ( sort keys %overlap ) {
2280                 $overlap += $overlap{$key};
2281                 $max = List::Util::max( $max, $overlap );
2282         }
2283         if ( wantarray ) {
2284                 return ( $max, $str );
2285         }
2286         else {
2287                 return $max;
2288         }
2289 }
2290
2291 sub get_file_list_wrapper {
2292         local $base_dir = shift;
2293         local $ptr = shift;
2294
2295         &get_file_list( $base_dir );
2296 }
2297
2298 sub get_file_list{
2299         my $dir = shift;
2300
2301         opendir ( DIR, $dir );
2302         my @list = sort readdir( DIR );
2303         closedir( DIR );
2304
2305         foreach my $file ( @list ) {
2306                 next if ( $file =~ /^\.{1,2}$/ );
2307                 if ( -d "$dir/$file" ){
2308                         &get_file_list("$dir/$file");
2309                 }
2310                 else{
2311                         $abs = "$dir/$file";
2312                         utf8::decode( $abs );
2313                         ( $rel ) = $abs =~ /^$base_dir\/(.*)$/;
2314                         $ptr->( $rel, $abs );
2315                 }
2316         }
2317 }
2318
2319 sub strisjoined {
2320         my $str = shift;
2321
2322         return $str =~ /.{4}-.{2}-.{2} .{2}:.{2}:.{2}/ ? 0 : 1;
2323 }
2324
2325 sub str2datetime {
2326         my $str    = shift;
2327         my @time;
2328
2329         if ( strisjoined( $str ) ) {
2330                 @time = $str =~ /(.{4})(.{2})(.{2})(.{2})(.{2})(.{2})/;
2331         }
2332         else {
2333                 @time = $str =~ /(.{4})-(.{2})-(.{2}) (.{2}):(.{2}):(.{2})/;
2334         }
2335         return DateTime->new(
2336                 year   => $time[0], month     => $time[1], day    => $time[2],
2337                 hour   => $time[3], minute    => $time[4], second => $time[5], 
2338                 locale => 'ja_JP' , time_zone => $tz
2339         );
2340 }
2341
2342 sub str2dayname {
2343         my  $str = shift;
2344         our %day_name_cache;
2345
2346         if ( !$day_name_cache{$str} ) {
2347                 $day_name_cache{$str} = str2datetime( $str )->day_name;
2348         }
2349         return $day_name_cache{$str};
2350 }
2351
2352 sub str2readable { 
2353         my $begin = shift;
2354         my $end   = shift;
2355
2356         my $dt_begin = ref( $begin ) eq 'DateTime' ? $begin : &str2datetime( $begin );
2357         my $dt_end   = ref( $end   ) eq 'DateTime' ? $end   : &str2datetime( $end );
2358
2359         my $str_begin = $dt_begin->strftime( '%m/%d(%a) %H:%M' );
2360         my $str_end   = $dt_end  ->strftime( $dt_begin->day == $dt_end->day ? '%H:%M' : '翌 %H:%M' );
2361         # utf8::encode( $str_begin );
2362
2363         my ( $sec, $min, $hour );
2364         $sec  = $dt_end->epoch - $dt_begin->epoch;
2365         $min  = int( $sec / 60 );
2366         $sec  = $sec - $min * 60;
2367         $hour = int( $min / 60 );
2368         $min  = $min - $hour * 60;
2369         my $str_diff = '';
2370         $str_diff .= $hour . '時間' if ( $hour );
2371         $str_diff .= $min  . '分'   if ( $min );
2372         $str_diff .= $sec  . '秒'   if ( $sec );
2373
2374         return ( $str_begin, $str_end, $str_diff );
2375 }
2376
2377 sub sqlgetsuggested {
2378         require Encode;
2379
2380         my ( $btime, $etime ) = @_;
2381         $deltatime = 3 if ( !$deltatime );
2382
2383         $btime_bgn = $btime->clone->subtract( hours => $deltatime )->strftime( '%Y%m%d%H%M%S' );
2384         $btime_end = $btime->clone->add(      hours => $deltatime )->strftime( '%Y%m%d%H%M%S' );
2385         $etime_bgn = $etime->clone->subtract( hours => $deltatime )->strftime( '%Y%m%d%H%M%S' );
2386         $etime_end = $etime->clone->add(      hours => $deltatime )->strftime( '%Y%m%d%H%M%S' );
2387
2388         $ary_ref = $dbh->selectall_arrayref(
2389                 "SELECT start, stop, title, exp 
2390                 FROM epg_timeline 
2391                 WHERE channel LIKE '$chtxt_sql' 
2392                 AND start BETWEEN '$btime_bgn' AND '$btime_end' 
2393                 AND stop  BETWEEN '$etime_bgn' AND '$etime_end' "
2394         );
2395         #die Dumper $ary_ref;
2396
2397         my %hash;
2398         my $hash_r = ngram_counts( $title, 2 ); # bi-gram
2399         foreach my $program ( @{$ary_ref} ) {
2400                 no warnings;
2401                 my $hash_k = ngram_counts( $program->[2], 2 );
2402                 my $point;
2403                 map $point += $hash_k->{$_}, keys %{$hash_r};
2404                 push @{$hash{$point}}, $program if ( $point );
2405         }
2406
2407         return %hash;
2408 }
2409
2410 sub ngram_counts {
2411         my $str  = shift;
2412         my $klen = shift;
2413         my $slen = length($str);  
2414
2415         my $href;
2416         for (my $i=0; $i < $slen-$klen+1; $i++){  
2417                 $href->{substr($str, $i, $klen)}++;
2418         }
2419         return $href;
2420 }
2421
2422 sub chtxt_format {
2423         ( $chtxt_0   = $chtxt ) =~ s/(\d+)_\d+/$1_0/;
2424         ( $chtxt_sql = $chtxt ) =~ s/(\d+)_\d+/$1_%/;
2425         if ( $bctype =~ /bs|cs/ ) {
2426                 $bctype_sql = '_s%';
2427         }
2428         elsif ( $bctype =~ /te/ ) {
2429                 $bctype_sql = 'te%';
2430         }
2431 }
2432