OSDN Git Service

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