OSDN Git Service

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