lilalo
view l3-frontend @ 138:93e08c4b54ed
typo fixed
| author | igor@chub.in | 
|---|---|
| date | Mon Jul 21 11:24:53 2008 +0300 (2008-07-21) | 
| parents | 58c869722fd0 | 
| children | c48bd05dca85 | 
 line source
     1 #!/usr/bin/perl
     3 use POSIX qw(strftime);
     4 use lib '/etc/lilalo';
     5 use l3config;
     6 use utf8;
     8 our @Command_Lines;
     9 our @Command_Lines_Index;
    10 our %Commands_Description;
    11 our %Args_Description;
    12 our %Sessions;
    14 our $debug_output="";      # Используйте эту переменную, если нужно передать отладочную информацию
    16 our %filter;
    17 our $filter_url;
    18 sub init_filter;
    20 our %Files;
    22 # vvv Инициализация переменных выполняется процедурой init_variables
    23 our @Day_Name;
    24 our @Month_Name;
    25 our @Of_Month_Name;
    26 our %Search_Machines;
    27 our %Elements_Visibility;
    28 # ^^^
    30 our $First_Command=$0;
    31 our $Last_Command=40;
    33 our %Stat;
    34 our %frequency_of_command; # Сколько раз в журнале встречается какая команда
    35 our $table_number=1;
    36 our %tigra_hints;
    38 my %mywi_cache_for;         # Кэш для экономии обращений к mywi
    40 sub count_frequency_of_commands;
    41 sub make_comment;
    42 sub make_new_entries_table;
    43 sub load_command_lines_from_xml;
    44 sub load_sessions_from_xml;
    45 sub sort_command_lines;
    46 sub process_command_lines;
    47 sub init_variables;
    48 sub main;
    49 sub collapse_list($);
    51 sub minutes_passed;
    53 sub print_all_txt;
    54 sub print_all_html;
    55 sub print_edit_all_html;
    56 sub print_command_lines_html;
    57 sub print_command_lines_txt;
    58 sub print_files_html;
    59 sub print_stat_html;
    60 sub print_header_html;
    61 sub print_footer_html;
    62 sub tigra_hints_generate;
    64 #### mywi
    65 # 
    66 sub mywi_init;
    67 sub load_mywitxt;
    68 sub mywi_process_query($);
    69 #
    70 sub add_to_log($$);
    71 sub parse_query;
    72 sub search_in_txt;
    73 sub add_to_log($$);
    74 sub mywi_guess($);
    75 #
    77 main();
    79 sub main
    80 {
    81     $| = 1;
    83     init_variables();
    84     init_config();
    85     $Config{frontend_ico_path}=$Config{frontend_css};
    86     $Config{frontend_ico_path}=~s@/[^/]*$@@;
    87     init_filter();
    88     mywi_init();
    90     load_command_lines_from_xml($Config{"backend_datafile"});
    91     load_sessions_from_xml($Config{"backend_datafile"});
    92     sort_command_lines;
    93     process_command_lines;
    94     if (defined($filter{action}) && $filter{action} eq "edit") {
    95         print_edit_all_html($Config{"output"});
    96     }
    97     else {
    98         print_all_html($Config{"output"});
    99     }
   100 }
   102 sub init_filter
   103 {
   104     if ($Config{filter}) {
   105         # Инициализация фильтра
   106         for (split /&/,$Config{filter}) {
   107             my ($var, $val) = split /=/;
   108             $filter{$var} = $val || "";
   109         }
   110     }
   111     $filter_url = join ("&", map("$_=$filter{$_}", keys %filter));
   112 }
   114 # extract_from_cline
   116 # In:   $what       = commands | args
   117 # Out:  return      ссылка на хэш, содержащий результаты разбора
   118 #                   команда => позиция
   120 # Разобрать командную строку $_[1] и возвратить хэш, содержащий 
   121 # номер первого появление команды в строке:
   122 #   команда => первая позиция
   123 sub extract_from_cline
   124 {
   125     my $what = $_[0];
   126     my $cline = $_[1];
   127     my @lists = split /\;/, $cline;
   130     my @command_lines = ();
   131     for my $command_list (@lists) {
   132         push(@command_lines, split(/\|/, $command_list));
   133     }
   135     my %position_of_command;
   136     my %position_of_arg;
   137     my $i=0;
   138     for my $command_line (@command_lines) {
   139         $command_line =~ s@^\s*@@;
   140         $command_line =~ /\s*(\S+)\s*(.*)/;
   141         if ($1 && $1 eq "sudo" ) {
   142             $position_of_command{"$1"}=$i++;
   143             $command_line =~ s/\s*sudo\s+//;
   144         }
   145         if ($command_line !~ m@^\s*\S*/etc/@) {
   146             $command_line =~ s@^\s*\S+/@@;
   147         }
   149         $command_line =~ /\s*(\S+)\s*(.*)/;
   150         my $command = $1;
   151         my $args = $2;
   152         if ($command && !defined $position_of_command{"$command"}) {
   153                 $position_of_command{"$command"}=$i++;
   154         };  
   155         if ($args) {
   156             my @args = split (/\s+/, $args);
   157             for my $a (@args) {
   158                 $position_of_arg{"$a"}=$i++
   159                     if !defined $position_of_arg{"$a"};
   160             };  
   161         }
   162     }
   164     if ($what eq "commands") {
   165         return \%position_of_command;
   166     } else {
   167         return \%position_of_arg;
   168     }
   170 }
   172 sub mywrap($)
   173 {
   174 return '<div class="t"><div class="b"><div class="l"><div class="r"><div class="bl"><div class="br"><div class="tl"><div class="tr">'.$_[0].
   175 '</div></div></div></div></div></div></div></div>';
   176 }
   178 sub tigra_hints_generate
   179 {
   180     my $tigra_hints_items="";
   181     for my $hint_id (keys %tigra_hints) {
   182         $tigra_hints{$hint_id} =~ s@\n@<br/>@gs;
   183         $tigra_hints{$hint_id} =~ s@ - @ — @gs;
   184         $tigra_hints{$hint_id} =~ s@'@\\'@gs;
   185 #        $tigra_hints_items .= "'$hint_id' : mywrap('".$tigra_hints{$hint_id}."'),";
   186         $tigra_hints_items .= "'$hint_id' : '".mywrap($tigra_hints{$hint_id})."',";
   187     }
   188     $tigra_hints_items =~ s/,$//; 
   189     return <<TIGRA;
   191 var HINTS_CFG = {
   192 	'top'        : 5, // a vertical offset of a hint from mouse pointer
   193 	'left'       : 5, // a horizontal offset of a hint from mouse pointer
   194 	'css'        : 'hintsClass', // a style class name for all hints, TD object
   195 	'show_delay' : 500, // a delay between object mouseover and hint appearing
   196 	'hide_delay' : 2000, // a delay between hint appearing and hint hiding
   197 	'wise'       : true,
   198 	'follow'     : true,
   199 	'z-index'    : 0 // a z-index for all hint layers
   200 },
   202 HINTS_CFG_NEW = {
   203     'wise'       : true, // don't go off screen, don't overlap the object in the document
   204     'margin'     : 10, // minimum allowed distance between the hint and the window edge (negative values accepted)
   205     'gap'        : 20, // minimum allowed distance between the hint and the origin (negative values accepted)
   206     'align'      : 'bctl', // align of the hint and the origin (by first letters origin's top|middle|bottom left|center|right to hint's top|middle|bottom left|center|right)
   207     'css'        : 'hintsClass', // a style class name for all hints, applied to DIV element (see style section in the header of the document)
   208     'show_delay' : 0, // a delay between initiating event (mouseover for example) and hint appearing
   209     'hide_delay' : 200, // a delay between closing event (mouseout for example) and hint disappearing
   210     'follow'     : true, // hint follows the mouse as it moves
   211     'z-index'    : 100, // a z-index for all hint layers
   212     'IEfix'      : false, // fix IE problem with windowed controls visible through hints (activate if select boxes are visible through the hints)
   213     'IEtrans'    : ['blendTrans(DURATION=.3)', null], // [show transition, hide transition] - nice transition effects, only work in IE5+
   214     'opacity'    : 90 // opacity of the hint in %%
   215 },
   217 HINTS_ITEMS = {
   218     $tigra_hints_items
   219 };
   220 var myHint = new THints (HINTS_CFG, HINTS_ITEMS);
   223 function mywrap (s_) {
   224 return '<div class="t"><div class="b"><div class="l"><div class="r"><div class="bl"><div class="br"><div class="tl"><div class="tr">'+s_+
   225 '</div></div></div></div></div></div></div></div>';
   227 }
   228 TIGRA
   229 $a=<<TIGRA;
   230 TIGRA
   231 }
   234 sub count_frequency_of_commands
   235 {
   236     my $cline = $_[0];
   237     my @commands = keys %{extract_from_cline("commands", $cline)};
   238     for my $command (@commands) {
   239         $frequency_of_command{$command}++;
   240     }
   241 }
   243 sub make_comment
   244 {
   245     my $cline = $_[0];
   246     #my $files = $_[1];
   248     my @comments;
   249     my @commands = keys %{extract_from_cline("commands", $cline)};
   250     my @args = keys %{extract_from_cline("args", $cline)};
   251     return if (!@commands && !@args);
   252     #return "commands=".join(" ",@commands)."; files=".join(" ",@files);
   254     # Commands
   255     for my $command (@commands) {
   256         $command =~ s/'//g;
   257         #$frequency_of_command{$command}++;
   258         if (!$Commands_Description{$command}) {
   259             $mywi_cache_for{$command} ||= mywi_process_query($command) || "";
   260             my $mywi = join ("\n", grep(/\([18]|sh|script\)/, split(/\n/, $mywi_cache_for{$command})));
   261             $mywi =~ s/\s+/ /;
   262             if ($mywi !~ /^\s*$/) {
   263                 $Commands_Description{$command} = $mywi;
   264             }
   265             else {
   266                 next;
   267             }
   268         }
   270         push @comments, $Commands_Description{$command};
   271     }
   272     return join("
\n", @comments);
   274     # Files
   275     for my $arg (@args) {
   276         $arg =~ s/'//g;
   277         if (!$Args_Description{$arg}) {
   278             my $mywi;
   279             $mywi = mywi_client ($arg);
   280             $mywi = join ("\n", grep(/\([5]\)/, split(/\n/, $mywi)));
   281             $mywi =~ s/\s+/ /;
   282             if ($mywi !~ /^\s*$/) {
   283                 $Args_Description{$arg} = $mywi;
   284             }
   285             else {
   286                 next;
   287             }
   288         }
   290         push @comments, $Args_Description{$arg};
   291     }
   293 }
   295 =cut
   296 Процедура load_command_lines_from_xml выполняет загрузку разобранного lab-скрипта
   297 из XML-документа в переменную @Command_Lines
   299 # In:       $datafile           имя файла
   300 # Out:      @CommandLines       загруженные командные строки
   302 Предупреждение!
   303 Процедура не в состоянии обрабатывать XML-документ любой структуры.
   304 В действительности файл cache из которого загружаются данные 
   305 просто напоминает XML с виду.
   306 =cut
   307 sub load_command_lines_from_xml
   308 {
   309     my $datafile = $_[0];
   311     open (CLASS, $datafile)
   312         or die "Can't open file with xml lablog ",$datafile,"\n";
   313     local $/;
   314     binmode CLASS, ":utf8";
   315     $data = <CLASS>;
   316     close(CLASS);
   318     for $command ($data =~ m@<command>(.*?)</command>@sg) {
   319         my %cl;
   320         while ($command =~ m@<([^>]*?)>(.*?)</\1>@sg) {
   321             $cl{$1} = $2;
   322         }
   323         push @Command_Lines, \%cl;
   324     }
   325 }
   327 sub load_sessions_from_xml
   328 {
   329     my $datafile = $_[0];
   331     open (CLASS,  $datafile)
   332         or die "Can't open file with xml lablog ",$datafile,"\n";
   333     local $/;
   334     binmode CLASS, ":utf8";
   335     my $data = <CLASS>;
   336     close(CLASS);
   338     my $i=0;
   339     for my $session ($data =~ m@<session>(.*?)</session>@msg) {
   340         my %session_hash;
   341         while ($session =~ m@<([^>]*?)>(.*?)</\1>@sg) {
   342             $session_hash{$1} = $2;
   343         }
   344         $Sessions{$session_hash{local_session_id}} = \%session_hash;
   345     }
   346 }
   349 # sort_command_lines
   350 # In:   @Command_Lines
   351 # Out:  @Command_Lies_Index
   353 sub sort_command_lines
   354 {
   356     my @index;
   357     for (my $i=0;$i<=$#Command_Lines;$i++) {
   358         $index[$i]=$i;
   359     }
   361     @Command_Lines_Index = sort {
   362         $Command_Lines[$index[$a]]->{"time"} <=> $Command_Lines[$index[$b]]->{"time"}
   363     } @index;
   365 }
   367 ##################
   368 # process_command_lines
   369 #
   370 # Обрабатываются командные строки @Command_Lines
   371 # Для каждой строки определяется:
   372 #   class   класс    
   373 #   note    комментарий 
   374 #
   375 # In:        @Command_Lines_Index
   376 # In-Out:    @Command_Lines
   378 sub process_command_lines
   379 {
   382     my $current_command=0;
   383     my $prev_i;
   385     my $tab_seq =0 ; # номер команды в последовательности tab-completion
   386                      # отличен от нуля только для тех последовательностей, 
   387                      # где постоянно нажимается клавиша tab
   389 COMMAND_LINE_PROCESSING:
   390     for my $i (@Command_Lines_Index) {
   392         $current_command++;
   393         next if $current_command < $Config{"start_from_command"};
   394         last if $current_command > $Config{"start_from_command"} + $Config{"commands_to_show_at_a_go"};
   396         my $cl = \$Command_Lines[$i];
   398         # Запоминаем предыщуюу команду
   399         # Она нам потребуется, в частности, для ввода tab_seq рпи обработке tab_completion
   400         my $prev_cl;
   401         $prev_cl = \$Command_Lines[$prev_i] if defined($prev_i);
   402         $prev_i = $i;
   404         next if !$cl;
   406         for my $filter_key (keys %filter) {
   407             next COMMAND_LINE_PROCESSING
   408                 if defined($$cl->{local_session_id})
   409                 && defined($Sessions{$$cl->{local_session_id}}->{$filter_key})
   410                 && $Sessions{$$cl->{local_session_id}}->{$filter_key} ne $filter{$filter_key};
   411         }
   413         $$cl->{id} = $$cl->{"time"};
   415         $$cl->{err} ||=0;
   418         # Класс команды
   420         $$cl->{"class"} =   $$cl->{"err"} eq 130 ?  "interrupted"
   421                         :   $$cl->{"err"} eq 127 ?  "mistyped"
   422                         :   $$cl->{"err"}        ?  "wrong"
   423                         :                           "normal";
   425         if ($$cl->{"cline"} && 
   426             $$cl->{"cline"} =~ /[^|`]\s*sudo/
   427             || $$cl->{"uid"} eq 0) {
   428             $$cl->{"class"}.="_root";
   429         }
   431         my $hint;
   432         count_frequency_of_commands($$cl->{"cline"});
   433         $hint = make_comment($$cl->{"cline"});
   435         if ($hint) {
   436             $$cl->{hint} = $hint;
   437         }
   438         $tigra_hints{$$cl->{"time"}} = $hint;
   440         #$$cl->{hint}="";
   442 # Выводим <head_lines> верхних строк
   443 # и <tail_lines> нижних строк,
   444 # если эти параметры существуют
   445         my $output="";
   447         if ($$cl->{"last_command"} eq "cat" && !$$cl->{"err"} && !($$cl->{"cline"} =~ /</)) {
   448             my $filename = $$cl->{"cline"};
   449             $filename =~ s/.*\s+(\S+)\s*$/$1/;
   450             $Files{$filename}->{"content"} = $$cl->{"output"};
   451            $Files{$filename}->{"source_command_id"} = $$cl->{"id"}
   452         }
   453         my @lines = split '\n', $$cl->{"output"};
   454         if ((
   455              $Config{"head_lines"} 
   456              || $Config{"tail_lines"}
   457              )
   458              && $#lines >  $Config{"head_lines"} + $Config{"tail_lines"} ) {
   459 #
   460             for (my $i=0; $i<= $#lines && $i < $Config{"head_lines"}; $i++) {
   461                 $output .= $lines[$i]."\n";
   462             }
   463             $output .= $Config{"skip_text"}."\n";
   465             my $start_line=$#lines-$Config{"tail_lines"}+1;
   466             for (my $i=$start_line; $i<= $#lines; $i++) {
   467                 $output .= $lines[$i]."\n";
   468             }
   469         } 
   470         else {
   471            $output = $$cl->{"output"};
   472         }
   473         $$cl->{short_output} = $output;
   475 # Обработка команд с одинаковым временем
   476 # Скорее всего они набраны с помощью tab-completion
   477         if (defined($prev_cl)) {
   478            if ($$prev_cl->{time} == $$cl->{time} && $$prev_cl->{nonce} == $$cl->{nonce}) {
   479             $tab_seq++;
   480            } 
   481            else {
   482             $tab_seq=0;
   483            };
   484            $$prev_cl->{tab_seq}=$tab_seq;
   486 # Обработка команд с одинаковым номером в истории
   487 # Скорее всего они набраны с помощью Ctrl-C
   488            #if ($$prev_cl->{history} == $$cl->{history}) {
   489            # $$prev_cl->{break}=1;
   490            #}
   491         }
   494 #Обработка пометок
   495 #  Если несколько пометок (notes) идут подряд, 
   496 #  они все объединяются
   498         if ($$cl->{cline} =~ /l3shot/) {
   499                 if ($$cl->{output} =~ m@Screenshot is written to.*/(.*)\.xwd@) {
   500                     $$cl->{screenshot}="$1".$Config{l3shot_suffix};
   501                 }
   502         }
   503         if ($$cl->{cline} =~ /l3upload/) {
   504                 if ($$cl->{output} =~ m@Uploaded file name is (.*)@) {
   505                     $$cl->{screenshot}="$1";
   506                 }
   507         }
   509         if ($$cl->{cline}=~ m@cat[^#]*#([\^=v])\s*(.*)@) {
   511             my $note_operator = $1;
   512             my $note_title = $2;
   514             if ($note_operator eq "=") {
   515                 $$cl->{"class"} = "note";
   516                 $$cl->{"note"} = $$cl->{"output"};
   517                 $$cl->{"note_title"} = $2;
   518             }
   519             else {
   520                 my $j = $i;
   521                 if ($note_operator eq "^") {
   522                     $j--;
   523                     $j-- while ($j >=0  && (!$Command_Lines[$j] || $Command_Lines[$j]->{tty} ne $$cl->{tty}));
   524                 }
   525                 elsif ($note_operator eq "v") {
   526                     $j++;
   527                     $j++ while ($j <= @Command_Lines  && (!$Command_Lines[$j] || $Command_Lines[$j]->{tty} ne $$cl->{tty}));
   528                 }
   529                 $Command_Lines[$j]->{note_title}=$note_title;
   530                 $Command_Lines[$j]->{note}.=$$cl->{output};
   531                 $$cl=0;
   532             }
   533         }
   534         elsif ($$cl->{cline}=~ /#([\^=v])(.*)/) {
   536             my $note_operator = $1;
   537             my $note_text = $2;
   539             if ($note_operator eq "=") {
   540                 $$cl->{"class"} = "note";
   541                 $$cl->{"note"} = $note_text;
   542             }
   543             else {
   544                 my $j=$i;
   545                 if ($note_operator eq "^") {
   546                     $j--;
   547                     $j-- while ($j >=0  && (!$Command_Lines[$j] || $Command_Lines[$j]->{tty} ne $$cl->{tty}));
   548                 }
   549                 elsif ($note_operator eq "v") {
   550                     $j++;
   551                     $j++ while ($j <= @Command_Lines  && $Command_Lines[$j]->{tty} ne $$cl->{tty} || !$Command_Lines[$j]);
   552                 }
   553                 $Command_Lines[$j]->{note}.="$note_text\n";
   554                 $$cl=0;
   555             }
   556         }
   557         if ($$cl->{"class"} eq "note") {
   558                 my $note_html = $$cl->{note};
   559                 $note_html = join ("\n", map ("<p>$_</p>", split (/-\n/, $note_html)));
   560                 $note_html =~ s@(http:[a-zA-Z.0-9/?\_%-]*)@<a href='$1'>$1</a>@g;
   561                 $note_html =~ s@(www\.[a-zA-Z.0-9/?\_%-]*)@<a href='$1'>$1</a>@g;
   562                 $$cl->{"note_html"} = $note_html;
   563         }
   564     }   
   566 }
   569 =cut
   570 Процедура print_command_lines выводит HTML-представление
   571 разобранного lab-скрипта. 
   573 Разобранный lab-скрипт должен находиться в массиве @Command_Lines
   574 =cut
   576 sub print_command_lines_html
   577 {
   579     my @toc;                # Оглавление
   580     my $note_number=0;
   582     my $result = q();
   583     my $this_day_resut = q();
   585     my $cl;
   586     my $last_tty="";
   587     my $last_session="";
   588     my $last_day=q();
   589     my $last_wday=q();
   590     my $first_command_of_the_day_unix_time=q();
   591     my $human_readable_time=q();
   592     my $in_range=0;
   594     my $current_command=0;
   596     my @known_commands;
   600     $Stat{LastCommand}   ||= 0;
   601     $Stat{TotalCommands} ||= 0;
   602     $Stat{ErrorCommands} ||= 0;
   603     $Stat{MistypedCommands} ||= 0;
   605     my %new_entries_of = (
   606         "1 1"     =>   "программы пользователя",
   607         "2 8"     =>   "программы администратора",
   608         "3 sh"    =>   "команды интерпретатора",
   609         "4 script"=>   "скрипты",
   610     );
   612 COMMAND_LINE:
   613     for my $k (@Command_Lines_Index) {
   615         my $cl=$Command_Lines[$Command_Lines_Index[$current_command++]];
   616         next unless $cl;
   618         next if $current_command < $Config{"start_from_command"};
   619         last if $current_command > $Config{"start_from_command"} + $Config{"commands_to_show_at_a_go"};
   623 # Пропускаем строки, которые противоречат фильтру
   624 # Если у нас недостаточно информации о том, подходит строка под  фильтр или нет, 
   625 # мы её выводим
   627         for my $filter_key (keys %filter) {
   628             next COMMAND_LINE 
   629                 if defined($cl->{local_session_id})
   630                 && defined($Sessions{$cl->{local_session_id}}->{$filter_key})
   631                 && $Sessions{$cl->{local_session_id}}->{$filter_key} ne $filter{$filter_key};
   632         }
   634 # Набираем статистику
   635 # Хэш %Stat
   637         $Stat{FirstCommand} = $cl->{time} unless $Stat{FirstCommand};
   638         if ($cl->{time} - $Stat{LastCommand} < $Config{stat_inactivity_interval}) {
   639             $Stat{TotalTime} += $cl->{time} - $Stat{LastCommand}
   640         }
   641         my $seconds_since_last_command = $cl->{time} - $Stat{LastCommand};
   643         if ($Stat{LastCommand} > $cl->{time}) {
   644                $result .= "Время идёт вспять<br/>";
   645         };
   646         $Stat{LastCommand} = $cl->{time};
   647         $Stat{TotalCommands}++;
   649 # Пропускаем строки, выходящие за границу "signature",
   650 # при условии, что границы указаны
   651 # Пропускаем неправильные/прерванные/другие команды
   652         if ($Config{"from"} && $cl->{"cline"} =~ /$Config{"signature"}\s*$Config{"from"}/) {
   653             $in_range=1;
   654             next;
   655         }
   656         if ($Config{"to"} && $cl->{"cline"} =~ /$Config{"signature"}\s*$Config{"to"}/) {
   657             $in_range=0;
   658             next;
   659         }
   660         next    if ($Config{"from"} && $Config{"to"}   && !$in_range) 
   661                 || ($Config{"skip_empty"} =~ /^y/i     && $cl->{"cline"} =~ /^\s*$/ )
   662                 || ($Config{"skip_wrong"} =~ /^y/i     && $cl->{"err"} != 0)
   663                 || ($Config{"skip_interrupted"} =~ /^y/i && $cl->{"err"} == 130);
   668 #
   669 ##
   670 ## Начинается собственно вывод
   671 ##
   672 #
   674 ### Сначала обрабатываем границы разделов
   675 ### Если тип команды "note", это граница
   677         if ($cl->{class} eq "note") {
   678             $this_day_result .= "<tr><td colspan='6'>"
   679                              .  "<h4 id='note$note_number'>".$cl->{note_title}."</h4>" if $cl->{note_title}
   680                              .  "".$cl->{note_html}."<p/><p/></td></tr>";
   682             if ($cl->{note_title}) {
   683                 push @{$toc[@toc]},"<a href='#note$note_number'>".$cl->{note_title}."</a>";
   684                 $note_number++;
   685             }
   686             next;
   687         }
   689         my ($sec,$min,$hour,$day,$mon,$year,$wday,$yday,$isdst) = localtime($cl->{time});
   692         # Добавляем спереди 0 для удобочитаемости
   693         $min  = "0".$min  if $min  =~ /^.$/;
   694         $hour = "0".$hour if $hour =~ /^.$/;
   695         $sec  = "0".$sec  if $sec  =~ /^.$/;
   697         $class=$cl->{"class"};
   698         $Stat{ErrorCommands}++          if $class =~ /wrong/;
   699         $Stat{MistypedCommands}++       if $class =~ /mistype/;
   701 # DAY CHANGE
   702         if ( $last_day ne $day) {
   703             $prev_unix_time=$first_command_of_the_day_unix_time;
   704             $first_command_of_the_day_unix_time = $cl->{time};
   705             $human_readable_time = strftime "%D", localtime($prev_unix_time);
   706             if ($last_day) {
   708 # Вычисляем разность множеств.
   709 # Что-то вроде этого, если бы так можно было писать:
   710 #   @new_commands = keys %frequency_of_command - @known_commands;
   713 # Выводим предыдущий день
   715                 $result .= "<h3 id='day_on_sec_$prev_unix_time'>".$Day_Name[$last_wday]." ($human_readable_time)</h3>";
   716                 for my $entry_class (sort keys %new_entries_of) {
   717                     my $table_caption = "Таблица ".$table_number++.".".$Day_Name[$last_wday]
   718                                         .". Новые ".$new_entries_of{$entry_class};
   719                     my $new_commands_section = make_new_entries_table(
   720                                                 $table_caption, 
   721                                                 $entry_class=~/[0-9]+\s+(.*)/, 
   722                                                 \@known_commands);
   723                 }
   724                 @known_commands = keys %frequency_of_command;
   725                 $result .= $this_day_result;
   726             }
   728 # Добавляем текущий день в оглавление
   730             $human_readable_time = strftime "%D", localtime($first_command_of_the_day_unix_time);
   731             push @toc, "<a href='#day_on_sec_$first_command_of_the_day_unix_time'>".$Day_Name[$wday]." ($human_readable_time)</a>\n";
   734             $last_day=$day;
   735             $last_wday=$wday;
   736             $this_day_result = q();
   737         }
   738         else {
   739             $this_day_result .= minutes_passed($seconds_since_last_command);
   740         }
   742         $this_day_result .= "<div class='command' id='command:".$cl->{"id"}."' >\n";
   744 # CONSOLE CHANGE
   745         if ($cl->{"tty"} && $last_tty ne $cl->{"tty"} && 0) {
   746             my $tty = $cl->{"tty"};
   747             $this_day_result .= "<div class='ttychange'>"
   748                                 . $tty
   749                                 ."</div>";
   750             $last_tty=$cl->{"tty"};
   751         }
   753 # Session change
   754         if ( $last_session ne $cl->{"local_session_id"}) {
   755             my $tty;
   756             if (defined $Sessions{$cl->{"local_session_id"}}->{"tty"}) {
   757                 $this_day_result .= "<div class='ttychange'><a href='?local_session_id=".$cl->{"local_session_id"}."'>"
   758                                 . $Sessions{$cl->{"local_session_id"}}->{"tty"}
   759                                 ."</a></div>";
   760             }
   761             $last_session=$cl->{"local_session_id"};
   762         }
   764 # TIME
   765         if ($Config{"show_time"} =~ /^y/i) {
   766             $this_day_result .= "<div class='time'>$hour:$min:$sec</div>" 
   767         }
   769 # COMMAND
   770         my $cline;
   771         $prompt_hint = join ("
", 
   772                          map("$_=$cl->{$_}", 
   773                            grep (!/^(output|short_output|diff)$/, 
   774                              sort(keys(%{$cl})))));
   776         $cl->{"prompt"} =~ s/ $//;
   777         $cline = "<span title='$prompt_hint' class='prompt'><a href='#".$cl->{time}."' id='".$cl->{time}."'>".$cl->{"prompt"}."</a></span>"
   778                 ."<span onmouseover=\"myHint.show('".$cl->{time}."')\" onmouseout=\"myHint.hide()\">".$cl->{"cline"}."</span>";
   779         $cline =~ s/\n//;
   781         if ($cl->{"hint"}) {
   782 #            $cline = "<span title='$cl->{hint}' class='with_hint'>$cline</span>" ;
   783             $cline = "<span class='with_hint'>$cline</span>" ;
   784         } 
   785         else {
   786             $cline = "<span class='without_hint'>$cline</span>";
   787         }
   789         $this_day_result .= "<DIV class='fixed_div'><table cellpadding='0' cellspacing='0'><tr><td>\n<div class='cblock_$cl->{class}'>\n";
   790         $this_day_result .= "<div class='cline'>" . $cline ;      #cline
   791         $this_day_result .= "<span title='Код завершения ".$cl->{"err"}."'>\n"
   792                          .  "<img src='".$Config{frontend_ico_path}."/error.png'/>\n"
   793                          .  "</span>\n" if ($cl->{"err"} and not $cl->{tab_seq} and not $cl->{break});
   794         $this_day_result .= "<span title='Tab completion ".$cl->{tab_seq}."'>\n"
   795                          .  "<img src='".$Config{frontend_ico_path}."/tab.png'/>\n"
   796                          .  "</span>\n" if $cl->{tab_seq};
   797         $this_day_result .= "<span title='Ctrl-C pressed'>\n"
   798                          .  "<img src='".$Config{frontend_ico_path}."/break.png'/>\n"
   799                          .  "</span>\n" if ($cl->{break} and not $cl->{tab_seq});
   800         $this_day_result .= "</div>\n";                             #cline
   802 # OUTPUT
   803         my $last_command = $cl->{"last_command"};
   804         if (!( 
   805         $Config{"suppress_editors"} =~ /^y/i && grep ($_ eq $last_command, @{$Config{"editors"}}) ||
   806         $Config{"suppress_pagers"}  =~ /^y/i && grep ($_ eq $last_command, @{$Config{"pagers"}}) ||
   807         $Config{"suppress_terminal"}=~ /^y/i && grep ($_ eq $last_command, @{$Config{"terminal"}})
   808             )) {
   809             $this_day_result .= "<pre class='output'>\n" . $cl->{short_output} . "</pre>\n";
   810         }
   812 # DIFF
   813         $this_day_result .= "<pre class='diff'>".$cl->{"diff"}."</pre>"
   814             if ( $Config{"show_diffs"} =~ /^y/i && $cl->{"diff"});
   815 # SHOT
   816         $this_day_result .= "<img src='"
   817                 .$Config{l3shot_path}
   818                 .$cl->{"screenshot"}
   819                 ."' alt ='screenshot id ".$cl->{"screenshot"}
   820                 ."'/>"
   821             if ( $Config{"show_screenshots"} =~ /^y/i && $cl->{"screenshot"});
   823 #NOTES
   824         if ( $Config{"show_notes"} =~ /^y/i && $cl->{"note"}) {
   825             my $note=$cl->{"note"};
   826             $note =~ s/\n/<br\/>\n/msg;
   827             if (not $note =~ s@(http:[a-zA-Z.0-9/_?%-]*)@<a href='$1'>$1</a>@g) {
   828               $note =~ s@(www\.[a-zA-Z.0-9/_?%-]*)@<a href='$1'>$1</a>@g;
   829             };
   830             $this_day_result .= "<div class='note'>";
   831             $this_day_result .= "<div class='note_title'>".$cl->{note_title}."</div>" if $cl->{note_title};
   832             $this_day_result .= "<div class='note_text'>".$note."</div>";
   833             $this_day_result .= "</div>\n";
   834         }
   836         # Вывод очередной команды окончен
   837         $this_day_result .= "</div>\n";                     # cblock
   838         $this_day_result .= "</td></tr></table></DIV>\n"
   839                          .  "</div>\n";                     # command
   840     }
   841     last: {
   842         $prev_unix_time=$first_command_of_the_day_unix_time;
   843         $first_command_of_the_day_unix_time = $cl->{time};
   844         $human_readable_time = strftime "%D", localtime($prev_unix_time);
   846         $result .= "<h3 id='day_on_sec_$prev_unix_time'>".$Day_Name[$last_wday]." ($human_readable_time)</h3>";
   848         for my $entry_class (keys %new_entries_of) {
   849             my $table_caption = "Таблица ".$table_number++.".".$Day_Name[$last_wday]
   850                               . ". Новые ".$new_entries_of{$entry_class};
   851             my $new_commands_section = make_new_entries_table(
   852                                         $table_caption, 
   853                                         $entry_class=~/[0-9]+\s+(.*)/, 
   854                                         \@known_commands);
   855         }
   856         @known_commands = keys %frequency_of_command;
   857         $result .= $this_day_result;
   858    }
   860     return ($result, collapse_list (\@toc));
   862 }
   864 #############
   865 # make_new_entries_table
   866 #
   867 # Напечатать таблицу неизвестных команд
   868 #
   869 # In:       $_[0]       table_caption
   870 #           $_[1]       entries_class
   871 #           @_[2..]     known_commands
   872 # Out:
   874 sub make_new_entries_table
   875 {
   876     my $table_caption;
   877     my $entries_class = shift;
   878     my @known_commands = @{$_[0]};
   879     my $result = "";
   881     my %count;
   882     my @new_commands = ();
   883     for my $c (keys %frequency_of_command, @known_commands) {
   884         $count{$c}++
   885     }
   886     for my $c (keys %frequency_of_command) {
   887         push @new_commands, $c if $count{$c} != 2;
   888     }
   890     my $new_commands_section;
   891     if (@new_commands){
   892         my $hint;
   893         for my $c (reverse sort { $frequency_of_command{$a} <=> $frequency_of_command{$b} } @new_commands) {
   894                 $hint = make_comment($c);
   895                 next unless $hint;
   896                 my ($command, $hint) = $hint =~ m/(.*?) \s*- \s*(.*)/;
   897                 next unless $command =~ s/\($entries_class\)//i;
   898                 $new_commands_section .= "<tr><td valign='top'>$command</td><td>$hint</td></tr>";
   899         }
   900     }
   901     if ($new_commands_section) {
   902         $result .= "<table class='new_commands_table' width='700' cellspacing='0' cellpadding='0'>"
   903                 .  "<tr class='new_commands_caption'>"
   904                 .  "<td colspan='2' align='right'>$table_caption</td>"
   905                 .  "</tr>"
   906                 .  "<tr class='new_commands_header'>"
   907                 .  "<td width=100>Команда</td><td width=600>Описание</td>"
   908                 .  "</tr>"
   909                 .  $new_commands_section 
   910                 .  "</table>"
   911     }
   912     return $result;
   913 }
   915 #############
   916 # minutes_passed
   917 #
   918 #
   919 #
   920 # In:       $_[0]       seconds_since_last_command
   921 # Out:                  "minutes passed" text
   923 sub minutes_passed
   924 {
   925         my $seconds_since_last_command = shift;
   926         my $result = "";
   927         if ($seconds_since_last_command > 7200) {
   928             my $hours_passed =  int($seconds_since_last_command/3600);
   929             my $passed_word  = $hours_passed % 10 == 1 ? "прошла"
   930                                                          : "прошло";
   931             my $hours_word   = $hours_passed % 10 == 1 ?   "часа":
   932                                                            "часов";
   933             $result .= "<div class='much_time_passed'>"
   934                     .  $passed_word." >".$hours_passed." ".$hours_word
   935                     .  "</div>\n";
   936         }
   937         elsif ($seconds_since_last_command > 600) {
   938             my $minutes_passed =  int($seconds_since_last_command/60);
   941             my $passed_word  = $minutes_passed % 100 > 10 
   942                             && $minutes_passed % 100 < 20 ? "прошло"
   943                              : $minutes_passed % 10 == 1  ? "прошла"
   944                                                           : "прошло";
   946             my $minutes_word = $minutes_passed % 100 > 10 
   947                             && $minutes_passed % 100 < 20 ? "минут" :
   948                                $minutes_passed % 10 == 1 ? "минута":
   949                                $minutes_passed % 10 == 0 ? "минут" :
   950                                $minutes_passed % 10  > 4 ? "минут" :
   951                                                            "минуты";
   953             if ($seconds_since_last_command < 1800) {
   954                 $result .= "<div class='time_passed'>"
   955                         .  $passed_word." ".$minutes_passed." ".$minutes_word
   956                         .  "</div>\n";
   957             }
   958             else {
   959                 $result .= "<div class='much_time_passed'>"
   960                         .  $passed_word." ".$minutes_passed." ".$minutes_word
   961                         .  "</div>\n";
   962             }
   963         }
   964         return $result;
   965 }
   967 #############
   968 # print_all_txt
   969 #
   970 # Вывести журнал в текстовом формате
   971 #
   972 # In:       $_[0]       output_filename
   973 # Out:
   975 sub print_command_lines_txt
   976 {
   978     my $output_filename=$_[0];
   979     my $note_number=0;
   981     my $result = q();
   982     my $this_day_resut = q();
   984     my $cl;
   985     my $last_tty="";
   986     my $last_session="";
   987     my $last_day=q();
   988     my $last_wday=q();
   989     my $in_range=0;
   991     my $current_command=0;
   993     my $cursor_position = 0;
   996     if ($Config{filter}) {
   997         # Инициализация фильтра
   998         for (split /&/,$Config{filter}) {
   999             my ($var, $val) = split /=/;
  1000             $filter{$var} = $val || "";
  1001         }
  1002     }
  1005 COMMAND_LINE:
  1006     for my $k (@Command_Lines_Index) {
  1008         my $cl=$Command_Lines[$Command_Lines_Index[$current_command++]];
  1009         next unless $cl;
  1012 # Пропускаем строки, которые противоречат фильтру
  1013 # Если у нас недостаточно информации о том, подходит строка под  фильтр или нет, 
  1014 # мы её выводим
  1016         for my $filter_key (keys %filter) {
  1017             next COMMAND_LINE 
  1018                 if defined($cl->{local_session_id})
  1019                 && defined($Sessions{$cl->{local_session_id}}->{$filter_key})
  1020                 && $Sessions{$cl->{local_session_id}}->{$filter_key} ne $filter{$filter_key};
  1021         }
  1023 # Пропускаем строки, выходящие за границу "signature",
  1024 # при условии, что границы указаны
  1025 # Пропускаем неправильные/прерванные/другие команды
  1026         if ($Config{"from"} && $cl->{"cline"} =~ /$Config{"signature"}\s*$Config{"from"}/) {
  1027             $in_range=1;
  1028             next;
  1029         }
  1030         if ($Config{"to"} && $cl->{"cline"} =~ /$Config{"signature"}\s*$Config{"to"}/) {
  1031             $in_range=0;
  1032             next;
  1033         }
  1034         next    if ($Config{"from"} && $Config{"to"}   && !$in_range) 
  1035                 || ($Config{"skip_empty"} =~ /^y/i     && $cl->{"cline"} =~ /^\s*$/ )
  1036                 || ($Config{"skip_wrong"} =~ /^y/i     && $cl->{"err"} != 0)
  1037                 || ($Config{"skip_interrupted"} =~ /^y/i && $cl->{"err"} == 130);
  1040 #
  1041 ##
  1042 ## Начинается собственно вывод
  1043 ##
  1044 #
  1046 ### Сначала обрабатываем границы разделов
  1047 ### Если тип команды "note", это граница
  1049         if ($cl->{class} eq "note") {
  1050             $this_day_result .= " === ".$cl->{note_title}." === \n" if $cl->{note_title};
  1051             $this_day_result .= $cl->{note}."\n";
  1052             next;
  1053         }
  1055         my ($sec,$min,$hour,$day,$mon,$year,$wday,$yday,$isdst) = localtime($cl->{time});
  1057         # Добавляем спереди 0 для удобочитаемости
  1058         $min  = "0".$min  if $min  =~ /^.$/;
  1059         $hour = "0".$hour if $hour =~ /^.$/;
  1060         $sec  = "0".$sec  if $sec  =~ /^.$/;
  1062         $class=$cl->{"class"};
  1064 # DAY CHANGE
  1065         if ( $last_day ne $day) {
  1066             if ($last_day) {
  1067                 $result .= "== ".$Day_Name[$last_wday]." == \n";
  1068                 $result .= $this_day_result;
  1069             }
  1070             $last_day   = $day;
  1071             $last_wday  = $wday;
  1072             $this_day_result = q();
  1073         }
  1075 # CONSOLE CHANGE
  1076         if ($cl->{"tty"} && $last_tty ne $cl->{"tty"} && 0) {
  1077             my $tty = $cl->{"tty"};
  1078             $this_day_result .= "         #l3: ------- другая консоль ----\n";
  1079             $last_tty=$cl->{"tty"};
  1080         }
  1082 # Session change
  1083         if ( $last_session ne $cl->{"local_session_id"}) {
  1084             $this_day_result .= "# ------------------------------------------------------------"
  1085                              .  "  l3: local_session_id=".$cl->{"local_session_id"}
  1086                              .  " ---------------------------------- \n";
  1087             $last_session=$cl->{"local_session_id"};
  1088         }
  1090 # TIME
  1091         my @nl_counter = split (/\n/, $result);
  1092         $cursor_position=length($result) - @nl_counter;
  1094         if ($Config{"show_time"} =~ /^y/i) {
  1095             $this_day_result .= "$hour:$min:$sec" 
  1096         }
  1098 # COMMAND
  1099         $this_day_result .= " ".$cl->{"prompt"}.$cl->{"cline"}."\n";
  1100         if ($cl->{"err"}) {
  1101             $this_day_result .= "         #l3: err=".$cl->{'err'}."\n";
  1102         }
  1104 # OUTPUT
  1105         my $last_command = $cl->{"last_command"};
  1106         if (!( 
  1107         $Config{"suppress_editors"} =~ /^y/i && grep ($_ eq $last_command, @{$Config{"editors"}}) ||
  1108         $Config{"suppress_pagers"}  =~ /^y/i && grep ($_ eq $last_command, @{$Config{"pagers"}}) ||
  1109         $Config{"suppress_terminal"}=~ /^y/i && grep ($_ eq $last_command, @{$Config{"terminal"}})
  1110             )) {
  1111             my $output = $cl->{short_output};
  1112             if ($output) {
  1113                  $output =~ s/^/         |/mg;
  1114             }
  1115             $this_day_result .= $output;
  1116         }
  1118 # DIFF
  1119         if ( $Config{"show_diffs"} =~ /^y/i && $cl->{"diff"}) {
  1120             my $diff = $cl->{"diff"};
  1121             $diff =~ s/^/         |/mg;
  1122             $this_day_result .= $diff;
  1123         };
  1124 # SHOT
  1125         if ($Config{"show_screenshots"} =~ /^y/i && $cl->{"screenshot"}) {
  1126             $this_day_result .= "         #l3: screenshot=".$cl->{'screenshot'}."\n";
  1127         }
  1129 #NOTES
  1130         if ( $Config{"show_notes"} =~ /^y/i && $cl->{"note"}) {
  1131             my $note=$cl->{"note"};
  1132             $note =~ s/\n/\n#^/msg;
  1133             $this_day_result .= "#^ == ".$cl->{note_title}." ==\n" if $cl->{note_title};
  1134             $this_day_result .= "#^ ".$note."\n";
  1135         }
  1137     }
  1138     last: {
  1139         $result .= "== ".$Day_Name[$last_wday]." == \n";
  1140         $result .= $this_day_result;
  1141    }
  1143    return $result;
  1147 }
  1149 #############
  1150 # print_edit_all_html
  1151 #
  1152 # Вывести страницу с текстовым представлением журнала для редактирования
  1153 #
  1154 # In:       $_[0]       output_filename
  1155 # Out:
  1157 sub print_edit_all_html
  1158 {
  1159     my $output_filename= shift;
  1160     my $result;
  1161     my $cursor_position = 0;
  1163     $result = print_command_lines_txt;
  1164     my $title = ">Журнал лабораторных работ. Правка";
  1166     $result = 
  1167                "<html>"
  1168                 ."<head>"
  1169                 ."<meta content='text/html; charset=utf-8' http-equiv='Content-Type' />"
  1170                 ."<link rel='stylesheet' href='$Config{frontend_css}' type='text/css'/>"
  1171                 ."<title>$title</title>"
  1172                 ."</head>"
  1173               ."<script>"
  1174               .$SetCursorPosition_JS
  1175               ."</script>"
  1176               ."<body onLoad='setCursorPosition(document.all.mytextarea, $cursor_position, $cursor_position+10)'>"
  1177               ."<h1>Журнал лабораторных работ. Правка</h1>"
  1178               ."<form>"
  1179               ."<textarea rows='30' cols='100' wrap='off' id='mytextarea'>$result</textarea>"
  1180               ."<br/><input type='submit' value='Сохранить' label='label'/>"
  1181               ."</form>"
  1182               ."<p>Внимательно правим, потом сохраняем</p>"
  1183               ."<p>Строки, начинающиеся символами #l3: можно трогать, только если точно знаешь, что делаешь</p>"
  1184               ."</body>"
  1185               ."</html>";
  1187     if ($output_filename eq "-") {
  1188         print $result;
  1189     }
  1190     else {
  1191         open(OUT, ">", $output_filename)
  1192             or die "Can't open $output_filename for writing\n";
  1193         binmode ":utf8";
  1194         print OUT "$result";
  1195         close(OUT);
  1196     }
  1197 }
  1199 #############
  1200 # print_all_txt
  1201 #
  1202 # Вывести страницу с текстовым представлением журнала для редактирования
  1203 #
  1204 # In:       $_[0]       output_filename
  1205 # Out:
  1207 sub print_all_txt
  1208 {
  1209     my $result;
  1211     $result = print_command_lines_txt;
  1213     $result =~ s/>/>/g;
  1214     $result =~ s/</</g;
  1215     $result =~ s/&/&/g;
  1217     if ($output_filename eq "-") {
  1218         print $result;
  1219     }
  1220     else {
  1221         open(OUT, ">:utf8", $output_filename)
  1222             or die "Can't open $output_filename for writing\n";
  1223         print OUT "$result";
  1224         close(OUT);
  1225     }
  1226 }
  1229 #############
  1230 # print_all_html
  1231 #
  1232 #
  1233 #
  1234 # In:       $_[0]       output_filename
  1235 # Out:
  1238 sub print_all_html
  1239 {
  1240     my $output_filename=$_[0];
  1242     my $result;
  1243     my ($command_lines,$toc)  = print_command_lines_html;
  1244     my $files_section         = print_files_html;
  1246     $result = $debug_output;
  1247     $result .= print_header_html($toc);
  1250 #    $result.= join " <br/>", keys %Sessions;
  1251 #    for my $sess (keys %Sessions) {
  1252 #            $result .= join " ", keys (%{$Sessions{$sess}});
  1253 #            $result .= "<br/>";
  1254 #    }
  1256     $result.= "<h2 id='log'>Журнал</h2>"       . $command_lines;
  1257     $result.= "<h2 id='files'>Файлы</h2>"      . $files_section if $files_section;
  1258     $result.= "<h2 id='stat'>Статистика</h2>"  . print_stat_html;
  1259     $result.= "<h2 id='help'>Справка</h2>"     . $Html_Help . "<br/>"; 
  1260     $result.= "<h2 id='about'>О программе</h2>". $Html_About. "<br/>"; 
  1261     $result.= print_footer_html;
  1263     if ($output_filename eq "-") {
  1264         binmode STDOUT, ":utf8";
  1265         print $result;
  1266     }
  1267     else {
  1268         open(OUT, ">:utf8", $output_filename)
  1269             or die "Can't open $output_filename for writing\n";
  1270         print OUT $result;
  1271         close(OUT);
  1272     }
  1273 }
  1275 #############
  1276 # print_header_html
  1277 #
  1278 #
  1279 #
  1280 # In:   $_[0]       Содержание
  1281 # Out:              Распечатанный заголовок
  1283 sub print_header_html
  1284 {
  1285     my $toc = $_[0];
  1286     my $course_name = $Config{"course-name"};
  1287     my $course_code = $Config{"course-code"};
  1288     my $course_date = $Config{"course-date"};
  1289     my $course_center = $Config{"course-center"};
  1290     my $course_trainer = $Config{"course-trainer"};
  1291     my $course_student = $Config{"course-student"};
  1293     my $title    = "Журнал лабораторных работ";
  1294     $title      .= " -- ".$course_student if $course_student;
  1295     if ($course_date) {
  1296         $title  .= " -- ".$course_date; 
  1297         $title  .= $course_code ? "/".$course_code 
  1298                                 : "";
  1299     }
  1300     else {
  1301         $title  .= " -- ".$course_code if $course_code;
  1302     }
  1304     # Управляющая форма
  1305     my $control_form .= "<div class='visibility_form' title='Выберите какие элементы должны быть показаны в журнале'>"
  1306                      .  "<span class='header'>Видимые элементы</span>"
  1307                      .  "<span class='window_controls'><a href='' onclick='' title='свернуть форму управления'>_</a> <a href='' onclick='' title='закрыть форму управления'>x</a></span>"
  1308                      .  "<div><form>\n";
  1309     for my $element (sort keys %Elements_Visibility)
  1310     {
  1311         my ($skip, @e) = split /\s+/, $element;
  1312         my $showhide = join "", map { "ShowHide('$_');" } @e ;
  1313         $control_form .= "<div><input type='checkbox' name='$e[0]' onclick=\"$showhide\" checked>".
  1314                 $Elements_Visibility{$element}.
  1315                 "</input></div>";
  1316     }
  1317     $control_form .= "</form>\n"
  1318                   .  "</div>\n";
  1321     # Управляющая форма отключена
  1322     # Она слишком сильно мешает, нужно что-то переделать
  1323     $control_form = "";
  1325     my $tigra_hints_array=tigra_hints_generate;
  1327     my $result;
  1328     $result = <<HEADER;
  1329     <html>
  1330     <head>
  1331     <meta content='text/html; charset=utf-8' http-equiv='Content-Type' />
  1332     <link rel='stylesheet' href='$Config{frontend_css}' type='text/css'/>
  1333     <title>$title</title>
  1334     </head>
  1335     <body>
  1336     <!--<script>
  1337     $Html_JavaScript
  1338     </script>-->
  1340 <!-- vvv Tigra Hints vvv -->
  1341 <script language="JavaScript" src="/tigra/hints.js"></script>
  1342 <!--<script language="JavaScript" src="/tigra/hints_cfg.js"></script>-->
  1343 <script>$tigra_hints_array</script>
  1344 <style>
  1345 /* a class for all Tigra Hints boxes, TD object */
  1346     .hintsClass
  1347         {text-align: left; font-size:80%; font-family: Verdana, Arial, Helvetica; background-color:#ffffee; padding: 0px 0px 0px 0px;}
  1348 /* this class is used by Tigra Hints wrappers */
  1349     .row
  1350         {background: white;}
  1353     .bl2 {border: 1px solid #e68200; background:url(/tigra/block/bl2.gif) 0 100% no-repeat; text-align:left}
  1354     .bl {background:url(/tigra/block/bl2.gif) 0 100% no-repeat; text-align:left}
  1355     .br {background:url(/tigra/block/br2.gif) 100% 100% no-repeat}
  1356     .tl {background:url(/tigra/block/tl2.gif) 0 0 no-repeat}
  1357     .tr {background:url(/tigra/block/tr2.gif) 100% 0 no-repeat; padding:10px}
  1358     .tr2 {background:url(/tigra/block/tr2.gif) 100% 0 no-repeat}
  1359     .t {background:url(/tigra/block/dot2.gif) 0 0 repeat-x}
  1360     .b {background:url(/tigra/block/dot2.gif) 0 100% repeat-x}
  1361     .l {background:url(/tigra/block/dot2.gif) 0 0 repeat-y}
  1362     .r {background:url(/tigra/block/dot2.gif) 100% 0 repeat-y}
  1365 </style>
  1366 <!-- ^^^ Tigra Hints ^^^ -->
  1368 <!--
  1369     .bl2 {border: 1px solid #e68200; background:url(/tigra/block/bl2.gif) 0 100% no-repeat; width:20em; text-align:center}
  1370     .bl {background:url(/tigra/block/bl2.gif) 0 100% no-repeat; width:20em; text-align:center}
  1371     .br {background:url(/tigra/block/br2.gif) 100% 100% no-repeat}
  1372     .tl {background:url(/tigra/block/tl2.gif) 0 0 no-repeat}
  1373     .tr {background:url(/tigra/block/tr2.gif) 100% 0 no-repeat; padding:10px}
  1374     .tr2 {background:url(/tigra/block/tr2.gif) 100% 0 no-repeat}
  1375     .t {background:url(/tigra/block/dot2.gif) 0 0 repeat-x; width:20em}
  1376     .b {background:url(/tigra/block/dot2.gif) 0 100% repeat-x}
  1377     .l {background:url(/tigra/block/dot2.gif) 0 0 repeat-y}
  1378     .r {background:url(/tigra/block/dot2.gif) 100% 0 repeat-y}
  1379 -->
  1382     <div class='edit_link'>
  1383     [ <a href='?action=edit&$filter_url'>править</a> ]
  1384     </div>
  1385     <h1 onmouseover="myHint.show('1')" onmouseout="myHint.hide()" class='lined_header'>Журнал лабораторных работ</h1>
  1386 HEADER
  1387     if (    $course_student 
  1388             || $course_trainer 
  1389             || $course_name 
  1390             || $course_code 
  1391             || $course_date 
  1392             || $course_center) {
  1393             $result .= "<p>";
  1394             $result .= "Выполнил $course_student<br/>"  if $course_student;
  1395             $result .= "Проверил $course_trainer <br/>" if $course_trainer;
  1396             $result .= "Курс "                          if $course_name 
  1397                                                             || $course_code 
  1398                                                             || $course_date;
  1399             $result .= "$course_name "                  if $course_name;
  1400             $result .= "($course_code)"                 if $course_code;
  1401             $result .= ", $course_date<br/>"            if $course_date;
  1402             $result .= "Учебный центр $course_center <br/>" if $course_center;
  1403             $result .= "Фильтр ".join(" ", map("$filter{$_}=$_", keys %filter))."<br/>" if %filter;
  1404             $result .= "</p>";
  1405     }
  1407     $result .= <<HEADER;
  1408     <table width='100%'>
  1409     <tr>
  1410     <td width='*'>
  1412     <table border=0 id='toc' class='toc'>
  1413     <tr>
  1414     <td>
  1415     <div class='toc_title'>Содержание</div>
  1416     <ul>
  1417         <li><a href='#log'>Журнал</a></li>
  1418         <ul>$toc</ul>
  1419         <li><a href='#files'>Файлы</a></li>
  1420         <li><a href='#stat'>Статистика</a></li>
  1421         <li><a href='#help'>Справка</a></li>
  1422         <li><a href='#about'>О программе</a></li>
  1423     </ul>
  1424     </td>
  1425     </tr>
  1426     </table>
  1428     </td>
  1429     <td valign='top' width=200>$control_form</td>
  1430     </tr>
  1431     </table>
  1432 HEADER
  1434     return $result;
  1435 }
  1438 #############
  1439 # print_footer_html
  1440 #
  1441 #
  1442 #
  1443 #
  1444 #
  1446 sub print_footer_html
  1447 {
  1448     return "</body>\n</html>\n";
  1449 }
  1454 #############
  1455 # print_stat_html
  1456 #
  1457 #
  1458 #
  1459 # In:
  1460 # Out:
  1462 sub print_stat_html
  1463 {
  1464     %StatNames = (
  1465         FirstCommand        => "Время первой команды журнала",
  1466         LastCommand         => "Время последней команды журнала",
  1467         TotalCommands       => "Количество командных строк в журнале",
  1468         ErrorsPercentage    => "Процент команд с ненулевым кодом завершения, %",
  1469         MistypesPercentage  => "Процент синтаксически неверно набранных команд, %",
  1470         TotalTime           => "Суммарное время работы с терминалом <sup><font size='-2'>*</font></sup>, час",
  1471         CommandsPerTime     => "Количество командных строк в единицу времени, команда/мин",
  1472         CommandsFrequency   => "Частота использования команд",
  1473         RareCommands        => "Частота использования этих команд < 0.5%",
  1474     );
  1475     @StatOrder = (
  1476         FirstCommand,
  1477         LastCommand,
  1478         TotalCommands,
  1479         ErrorsPercentage,
  1480         MistypesPercentage,
  1481         TotalTime,
  1482         CommandsPerTime,
  1483         CommandsFrequency,
  1484         RareCommands,
  1485     );
  1487     # Подготовка статистики к выводу
  1488     # Некоторые значения пересчитываются!
  1489     # Дальше их лучше уже не использовать!!!
  1491     my %CommandsFrequency = %frequency_of_command;
  1493     $Stat{TotalTime} ||= 0;
  1494     my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($Stat{FirstCommand} || 0);
  1495     $Stat{FirstCommand} = sprintf "%02i:%02i:%02i %04i-%2i-%2i", $hour, $min, $sec,  $year+1900, $mon+1, $mday;
  1496     ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($Stat{LastCommand} || 0);
  1497     $Stat{LastCommand} = sprintf "%02i:%02i:%02i %04i-%2i-%2i", $hour, $min, $sec,  $year+1900, $mon+1, $mday;
  1498     if ($Stat{TotalCommands}) {
  1499         $Stat{ErrorsPercentage} = sprintf "%5.2f", $Stat{ErrorCommands}*100/$Stat{TotalCommands};
  1500         $Stat{MistypesPercentage} = sprintf "%5.2f", $Stat{MistypedCommands}*100/$Stat{TotalCommands};
  1501     }
  1502     $Stat{CommandsPerTime} = sprintf "%5.2f", $Stat{TotalCommands}*60/$Stat{TotalTime}
  1503         if $Stat{TotalTime};
  1504     $Stat{TotalTime} = sprintf "%5.2f", $Stat{TotalTime}/60/60;
  1506     my $total_commands=0;
  1507     for $command (keys %CommandsFrequency){
  1508         $total_commands += $CommandsFrequency{$command};
  1509     }
  1510     if ($total_commands) {
  1511         for $command (reverse sort {$CommandsFrequency{$a} <=> $CommandsFrequency{$b}} keys %CommandsFrequency){
  1512             my $command_html;
  1513             my $percentage = sprintf "%5.2f",$CommandsFrequency{$command}*100/$total_commands;
  1514             if ($percentage < 0.5) {
  1515                 my $hint = make_comment($command);
  1516                 $command_html = "$command";
  1517                 $command_html = "<span title='$hint' class='with_hint'>$command_html</span>" if $hint;
  1518                 $command_html = "<span class='without_hint'>$command_html</span>" if not $hint;
  1519                 my $command_html = "<tt>$command_html</tt>";
  1520                 $Stat{RareCommands} .= $command_html."<sub><font size='-2'>".$CommandsFrequency{$command}."</font></sub> , ";
  1521             }
  1522             else {
  1523                 my $hint = make_comment($command);
  1524                 $command_html = "$command";
  1525                 $command_html = "<span title='$hint' class='with_hint'>$command_html</span>" if $hint;
  1526                 $command_html = "<span class='without_hint'>$command_html</span>" if not $hint;
  1527                 my $command_html = "<tt>$command_html</tt>";
  1528                 $percentage = sprintf "%5.2f",$percentage;
  1529                 $Stat{CommandsFrequency} .= "<tr><td>".$command_html."</td><td>".$CommandsFrequency{$command}."</td>".
  1530                     "<td>|".("="x int($CommandsFrequency{$command}*100/$total_commands))."| $percentage%</td></tr>";
  1531             }
  1532         }
  1533         $Stat{CommandsFrequency} = "<table>".$Stat{CommandsFrequency}."</table>";
  1534         $Stat{RareCommands} =~ s/, $// if $Stat{RareCommands};
  1535     }
  1537     my $result = q();
  1538     for my $stat (@StatOrder) {
  1539         next unless $Stat{"$stat"};
  1540         $result .= "<tr valign='top'><td width='300'>".$StatNames{"$stat"}."</td><td>".$Stat{"$stat"}."</td></tr>"
  1541     }
  1542     $result  = "<table>$result</table>"
  1543              . "<font size='-2'>____<br/>*) Интервалы неактивности длительностью "
  1544              .  ($Config{stat_inactivity_interval}/60)
  1545              . " минут и более не учитываются</font></br>";
  1547     return $result;
  1548 }
  1551 sub collapse_list($)
  1552 {
  1553     my $res = "";
  1554     for my $elem (@{$_[0]}) {
  1555         if (ref $elem eq "ARRAY") {
  1556             $res .= "<ul>".collapse_list($elem)."</ul>";
  1557         }
  1558         else
  1559         {
  1560             $res .= "<li>".$elem."</li>";
  1561         }
  1562     }
  1563     return $res;
  1564 }
  1567 sub print_files_html
  1568 {
  1569     my $result = qq(); 
  1570     my @toc;
  1571     for my $file (sort keys %Files) {
  1572           my $div_id = "file:$file";
  1573           $div_id =~ s@/@_@g;
  1574           push @toc, "<a href='#$div_id'>$file</a>";
  1575           $result .= "<div class='filename' id='$div_id'>".$file."</div>\n"
  1576                   .  "<div class='file_navigation'><a href='#command:".$Files{$file}->{source_command_id}."'>".">"."</a></div>"
  1577                   .  "<div class='filedata'><pre>".$Files{$file}->{content}."</pre></div>";
  1578     }
  1579     if ($result) {
  1580         return "<div class='files_toc'>".collapse_list(\@toc)."</div>".$result;
  1581     } 
  1582     else {
  1583         return "";
  1584     }
  1585 }
  1588 sub init_variables
  1589 {
  1590 $Html_Help = <<HELP;
  1591     Для того чтобы использовать LiLaLo, не нужно знать ничего особенного:
  1592     всё происходит само собой.
  1593     Однако, чтобы ведение и последующее использование журналов
  1594     было как можно более эффективным, желательно иметь в виду следующее:
  1595     <ol>
  1596     <li><p> 
  1597     В журнал автоматически попадают все команды, данные в любом терминале системы.
  1598     </p></li>
  1599     <li><p>
  1600     Для того чтобы убедиться, что журнал на текущем терминале ведётся, 
  1601     и команды записываются, дайте команду w.
  1602     В поле WHAT, соответствующем текущему терминалу, 
  1603     должна быть указана программа script.
  1604     </p></li>
  1605     <li><p>
  1606     Команды, при наборе которых были допущены синтаксические ошибки, 
  1607     выводятся перечёркнутым текстом:
  1608 <table>
  1609 <tr class='command'>
  1610 <td class='script'>
  1611 <pre class='_mistyped_cline'>
  1612 \$ l s-l</pre>
  1613 <pre class='_mistyped_output'>bash: l: command not found
  1614 </pre>
  1615 </td>
  1616 </tr>
  1617 </table>
  1618 <br/>
  1619     </p></li>
  1620     <li><p>
  1621     Если код завершения команды равен нулю, 
  1622     команда была выполнена без ошибок.
  1623     Команды, код завершения которых отличен от нуля, выделяются цветом.
  1624 <table>
  1625 <tr class='command'>
  1626 <td class='script'>
  1627 <pre class='_wrong_cline'>
  1628 \$ test 5 -lt 4</pre>
  1629 </pre>
  1630 </td>
  1631 </tr>
  1632 </table>
  1633     Обратите внимание на то, что код завершения команды может быть отличен от нуля
  1634     не только в тех случаях, когда команда была выполнена с ошибкой.
  1635     Многие команды используют код завершения, например, для того чтобы показать результаты проверки
  1636 <br/>
  1637     </p></li>
  1638     <li><p>
  1639     Команды, ход выполнения которых был прерван пользователем, выделяются цветом.
  1640 <table>
  1641 <tr class='command'>
  1642 <td class='script'>
  1643 <pre class='_interrupted_cline'>
  1644 \$ find / -name abc</pre>
  1645 <pre class='interrupted_output'>find: /home/devi-orig/.gnome2: Keine Berechtigung
  1646 find: /home/devi-orig/.gnome2_private: Keine Berechtigung
  1647 find: /home/devi-orig/.nautilus/metafiles: Keine Berechtigung
  1648 find: /home/devi-orig/.metacity: Keine Berechtigung
  1649 find: /home/devi-orig/.inkscape: Keine Berechtigung
  1650 ^C
  1651 </pre>
  1652 </td>
  1653 </tr>
  1654 </table>
  1655 <br/>
  1656     </p></li>
  1657     <li><p>
  1658     Команды, выполненные с привилегиями суперпользователя,
  1659     выделяются слева красной чертой.
  1660 <table>
  1661 <tr class='command'>
  1662 <td class='script'>
  1663 <pre class='_root_cline'>
  1664 # id</pre>
  1665 <pre class='_root_output'>
  1666 uid=0(root) gid=0(root) Gruppen=0(root)
  1667 </pre>
  1668 </td>
  1669 </tr>
  1670 </table>
  1671     <br/>
  1672     </p></li>
  1673     <li><p>
  1674     Изменения, внесённые в текстовый файл с помощью редактора, 
  1675     запоминаются и показываются в журнале в формате ed.
  1676     Строки, начинающиеся символом "<", удалены, а строки,
  1677     начинающиеся символом ">" -- добавлены.
  1678 <table>
  1679 <tr class='command'>
  1680 <td class='script'>
  1681 <pre class='cline'>
  1682 \$ vi ~/.bashrc</pre>
  1683 <table><tr><td width='5'/><td class='diff'><pre>2a3,5
  1684 >    if [ -f /usr/local/etc/bash_completion ]; then
  1685 >         . /usr/local/etc/bash_completion
  1686 >        fi
  1687 </pre></td></tr></table></td>
  1688 </tr>
  1689 </table>
  1690     <br/>
  1691     </p></li>
  1692     <li><p>
  1693     Для того чтобы изменить файл в соответствии с показанными в диффшоте
  1694     изменениями, можно воспользоваться командой patch.
  1695     Нужно скопировать изменения, запустить программу patch, указав в
  1696     качестве её аргумента файл, к которому применяются изменения,
  1697     и всавить скопированный текст:
  1698 <table>
  1699 <tr class='command'>
  1700 <td class='script'>
  1701 <pre class='cline'>
  1702 \$ patch ~/.bashrc</pre>
  1703 </td>
  1704 </tr>
  1705 </table>
  1706     В данном случае изменения применяются к файлу ~/.bashrc
  1707     </p></li>
  1708     <li><p>
  1709     Для того чтобы получить краткую справочную информацию о команде, 
  1710     нужно подвести к ней мышь. Во всплывающей подсказке появится краткое
  1711     описание команды.
  1712     </p>
  1713     <p>
  1714     Если справочная информация о команде есть, 
  1715     команда выделяется голубым фоном, например: <span class="with_hint" title="главный текстовый редактор Unix">vi</span>.
  1716     Если справочная информация отсутствует,
  1717     команда выделяется розовым фоном, например: <span class="without_hint">notepad.exe</span>.
  1718     Справочная информация может отсутствовать в том случае, 
  1719     если (1) команда введена неверно; (2) если распознавание команды LiLaLo выполнено неверно;
  1720     (3) если информация о команде неизвестна LiLaLo.
  1721     Последнее возможно для редких команд.
  1722     </p></li>
  1723     <li><p>
  1724     Большие, в особенности многострочные, всплывающие подсказки лучше 
  1725     всего показываются браузерами KDE Konqueror, Apple Safari и Microsoft Internet Explorer.
  1726     В браузерах Mozilla и Firefox они отображаются не полностью, 
  1727     а вместо перевода строки выводится специальный символ.
  1728     </p></li>
  1729     <li><p>
  1730     Время ввода команды, показанное в журнале, соответствует времени 
  1731     <i>начала ввода командной строки</i>, которое равно тому моменту, 
  1732     когда на терминале появилось приглашение интерпретатора
  1733     </p></li>
  1734     <li><p>
  1735     Имя терминала, на котором была введена команда, показано в специальном блоке.
  1736     Этот блок показывается только в том случае, если терминал
  1737     текущей команды отличается от терминала предыдущей.
  1738     </p></li>
  1739     <li><p>
  1740     Вывод не интересующих вас в настоящий момент элементов журнала,
  1741     таких как время, имя терминала и других, можно отключить.
  1742     Для этого нужно воспользоваться <a href='#visibility_form'>формой управления журналом</a>
  1743     вверху страницы.
  1744     </p></li>
  1745     <li><p>
  1746     Небольшие комментарии к командам можно вставлять прямо из командной строки.
  1747     Комментарий вводится прямо в командную строку, после символов #^ или #v.
  1748     Символы ^ и v показывают направление выбора команды, к которой относится комментарий:
  1749     ^ - к предыдущей, v - к следующей.
  1750     Например, если в командной строке было введено:
  1751 <pre class='cline'>
  1752 \$ whoami
  1753 </pre>
  1754 <pre class='output'>
  1755 user
  1756 </pre>
  1757 <pre class='cline'>
  1758 \$ #^ Интересно, кто я?
  1759 </pre>
  1760     в журнале это будет выглядеть так:
  1762 <pre class='cline'>
  1763 \$ whoami
  1764 </pre>
  1765 <pre class='output'>
  1766 user
  1767 </pre>
  1768 <table class='note'><tr><td width='100%' class='note_text'>
  1769 <tr> <td> Интересно, кто я?<br/> </td></tr></table> 
  1770     </p></li>
  1771     <li><p>
  1772     Если комментарий содержит несколько строк,
  1773     его можно вставить в журнал следующим образом:
  1774 <pre class='cline'>
  1775 \$ whoami
  1776 </pre>
  1777 <pre class='output'>
  1778 user
  1779 </pre>
  1780 <pre class='cline'>
  1781 \$ cat > /dev/null #^ Интересно, кто я?
  1782 </pre>
  1783 <pre class='output'>
  1784 Программа whoami выводит имя пользователя, под которым 
  1785 мы зарегистрировались в системе.
  1786 -
  1787 Она не может ответить на вопрос о нашем назначении 
  1788 в этом мире.
  1789 </pre>
  1790     В журнале это будет выглядеть так:
  1791 <table>
  1792 <tr class='command'>
  1793 <td class='script'>
  1794 <pre class='cline'>
  1795 \$ whoami</pre>
  1796 <pre class='output'>user
  1797 </pre>
  1798 <table class='note'><tr><td class='note_title'>Интересно, кто я?</td></tr><tr><td width='100%' class='note_text'>
  1799 Программа whoami выводит имя пользователя, под которым<br/>
  1800 мы зарегистрировались в системе.<br/>
  1801 <br/>
  1802 Она не может ответить на вопрос о нашем назначении<br/>
  1803 в этом мире.<br/>
  1804 </td></tr></table>
  1805 </td>
  1806 </tr>
  1807 </table>
  1808     Для разделения нескольких абзацев между собой
  1809     используйте символ "-", один в строке.
  1810     <br/>
  1811 </p></li>
  1812     <li><p>
  1813     Комментарии, не относящиеся непосредственно ни к какой из команд, 
  1814     добавляются точно таким же способом, только вместо симолов #^ или #v 
  1815     нужно использовать символы #=
  1816     </p></li>
  1818     <p><li>
  1819     Содержимое файла может быть показано в журнале.
  1820     Для этого его нужно вывести с помощью программы cat.
  1821     Если вывод команды отметить симоволами #!, 
  1822     содержимое файла будет показано в журнале
  1823     в специально отведённой для этого секции.
  1824     </li></p>
  1826     <p>
  1827     <li>
  1828     Для того чтобы вставить скриншот интересующего вас окна в журнал,
  1829     нужно воспользоваться командой l3shot.
  1830     После того как команда вызвана, нужно с помощью мыши выбрать окно, которое
  1831     должно быть в журнале.
  1832     </li>
  1833     </p>
  1835     <p>
  1836     <li>
  1837     Команды в журнале расположены в хронологическом порядке.
  1838     Если две команды давались одна за другой, но на разных терминалах,
  1839     в журнале они будут рядом, даже если они не имеют друг к другу никакого отношения.
  1840 <pre>
  1841 1
  1842     2
  1843 3   
  1844     4
  1845 </pre>
  1846     Группы команд, выполненных на разных терминалах, разделяются специальной линией.
  1847     Под этой линией в правом углу показано имя терминала, на котором выполнялись команды.
  1848     Для того чтобы посмотреть команды только одного сенса, 
  1849     нужно щёкнуть по этому названию.
  1850     </li>
  1851     </p>
  1852 </ol>
  1853 HELP
  1855 $Html_About = <<ABOUT;
  1856     <p>
  1857     <a href='http://xgu.ru/lilalo/'>LiLaLo</a> (L3) расшифровывается как Live Lab Log.<br/>
  1858     Программа разработана для повышения эффективности обучения Unix/Linux-системам.<br/>
  1859     (c) Игорь Чубин, 2004-2008<br/>
  1860     </p>
  1861 ABOUT
  1862 $Html_About.='$Id$ </p>';
  1864 $Html_JavaScript = <<JS;
  1865     function getElementsByClassName(Class_Name)
  1866     {
  1867         var Result=new Array();
  1868         var All_Elements=document.all || document.getElementsByTagName('*');
  1869         for (i=0; i<All_Elements.length; i++)
  1870             if (All_Elements[i].className==Class_Name)
  1871         Result.push(All_Elements[i]);
  1872         return Result;
  1873     }
  1874     function ShowHide (name)
  1875     {
  1876         elements=getElementsByClassName(name);
  1877         for(i=0; i<elements.length; i++)
  1878             if (elements[i].style.display == "none")
  1879                 elements[i].style.display = "";
  1880             else
  1881                 elements[i].style.display = "none";
  1882             //if (elements[i].style.visibility == "hidden")
  1883             //  elements[i].style.visibility = "visible";
  1884             //else
  1885             //  elements[i].style.visibility = "hidden";
  1886     }
  1887     function filter_by_output(text)
  1888     {
  1890         var jjj=0;
  1892         elements=getElementsByClassName('command');
  1893         for(i=0; i<elements.length; i++) {
  1894             subelems = elements[i].getElementsByTagName('pre');
  1895             for(j=0; j<subelems.length; j++) {
  1896                 if (subelems[j].className = 'output') {
  1897                     var str = new String(subelems[j].nodeValue);
  1898                     if (jjj != 1) { 
  1899                         alert(str);
  1900                         jjj=1;
  1901                     }
  1902                     if (str.indexOf(text) >0) 
  1903                         subelems[j].style.display = "none";
  1904                     else
  1905                         subelems[j].style.display = "";
  1907                 }
  1909             }
  1910         }       
  1912     }
  1913 JS
  1915 $SetCursorPosition_JS = <<JS;
  1916 function setCursorPosition(oInput,oStart,oEnd) {
  1917     oInput.focus();
  1918     if( oInput.setSelectionRange ) {
  1919         oInput.setSelectionRange(oStart,oEnd);
  1920     } else if( oInput.createTextRange ) {
  1921         var range = oInput.createTextRange();
  1922         range.collapse(true);
  1923         range.moveEnd('character',oEnd);
  1924         range.moveStart('character',oStart);
  1925         range.select();
  1926     }
  1927 }
  1928 JS
  1930 %Search_Machines = (
  1931         "google" =>     {   "query" =>  "http://www.google.com/search?q=" ,
  1932                     "icon"  =>  "$Config{frontend_google_ico}" },
  1933         "freebsd" =>    {   "query" =>  "http://www.freebsd.org/cgi/man.cgi?query=",
  1934                     "icon"  =>  "$Config{frontend_freebsd_ico}" },
  1935         "linux"  =>     {   "query" =>  "http://man.he.net/?topic=",
  1936                     "icon"  =>  "$Config{frontend_linux_ico}"},
  1937         "opennet"  =>   {   "query" =>  "http://www.opennet.ru/search.shtml?words=",
  1938                     "icon"  =>  "$Config{frontend_opennet_ico}"},
  1939         "local" =>  {   "query" =>  "http://www.freebsd.org/cgi/man.cgi?query=",
  1940                     "icon"  =>  "$Config{frontend_local_ico}" },
  1942     );
  1944 %Elements_Visibility = (
  1945         "0 new_commands_table"      =>  "новые команды",
  1946         "1 diff"      =>  "редактор",
  1947         "2 time"      =>  "время",
  1948         "3 ttychange"     =>  "терминал",
  1949         "4 wrong_output wrong_cline wrong_root_output wrong_root_cline" 
  1950                 =>  "команды с ненулевым кодом завершения",
  1951         "5 mistyped_output mistyped_cline mistyped_root_output mistyped_root_cline" 
  1952                 =>  "неверно набранные команды",
  1953         "6 interrupted_output interrupted_cline interrupted_root_output interrupted_root_cline" 
  1954                 =>  "прерванные команды",
  1955         "7 tab_completion_output tab_completion_cline"    
  1956                 =>  "продолжение с помощью tab"
  1957 );
  1959 @Day_Name      = qw/ Воскресенье Понедельник Вторник Среда Четверг Пятница Суббота /;
  1960 @Month_Name    = qw/ Январь Февраль Март Апрель Май Июнь Июль Август Сентябрь Октябрь Ноябрь Декабрь /;
  1961 @Of_Month_Name = qw/ Января Февраля Марта Апреля Мая Июня Июля Августа Сентября Октября Ноября Декабря /;
  1962 }
  1967 # Временно удалённый код
  1968 # Возможно, он не понадобится уже никогда
  1971 sub search_by
  1972 {
  1973     my $sm = shift;
  1974     my $topic = shift;
  1975     $topic =~ s/ /+/;
  1977     return "<a href='". $Search_Machines{$sm}->{"query"}."$topic'><img width='16' height='16' src='".
  1978                 $Search_Machines{$sm}->{"icon"}."' border='0'/></a>";
  1979 }
  1984 ########################################################################################
  1985 #
  1986 # mywi
  1987 #
  1988 # 
  1989 #
  1990 #
  1991 #
  1992 #
  1993 #
  1997 sub mywi_init
  1998 {
  1999     our $MyWiFile = "/home/igor/mywi/mywi.txt";
  2000     our $MyWiLog = "/home/igor/mywi/mywi.log";
  2001     our $section="";
  2003     our @MywiTXT;       # Массив текстовых записей mywi
  2004     our %MywiHASH;      # Хэш массивов записей
  2005     our %Query;
  2007     load_mywitxt($MyWiFile, \@MywiTXT, \%MywiHASH);
  2008 }
  2010 sub mywi_process_query($)
  2011 #
  2012 # Сделать подсказку по заданному запросу
  2013 # $_[0] - тема для подсказки
  2014 # 
  2015 # Возвращает:
  2016 #   строку-подсказку
  2017 #
  2018 {
  2019     my $query = shift;
  2020     parse_query($query, \%Query);
  2021     $result = search_in_txt(\%Query, \@MywiTXT, \%MywiHASH);
  2023     if (!$result) {
  2024         #add_to_log(\%Query, $MyWiLog);
  2025         return "$query nothing appropriate.  Logged. ".join (";",%Query);
  2026     }   
  2028     return $result;
  2029 }
  2031 ####################################################################################
  2032 #                                   private section
  2033 ####################################################################################
  2035 sub load_mywitxt
  2036 #
  2037 # Загрузить файл с записями Mywi_TXT
  2038 # в массив
  2039 # $_[0] - указатель на массив для загрузки
  2040 # $_[1] - имя файла для загрузки
  2041 # 
  2042 {
  2043     my $MyWiFile = $_[0];
  2044     my $MywiTXT = $_[1];
  2045     my $MywiHASH = $_[2];
  2047     open (MW, "$MyWiFile") or die "Can't open $MyWiFile for reading";
  2048     binmode MW, ":utf8";
  2049     @{$MywiTXT} = <MW>;
  2050     close (MWF);
  2052     for my $mywi_line (@{$MywiTXT}) {
  2053         my $topic = $mywi_line;
  2054         $topic =~ s@\s*\(.*\n@@;
  2055         push @{$$MywiHASH{"$topic"}}, $mywi_line;
  2056 #        $MywiHASH{"$topic"} .= $mywi_line;
  2057     }
  2058 }
  2060 sub parse_query
  2061 #
  2062 # Строка запроса:
  2063 #   [format:]topic[(section)]
  2064 # Элементы format и topic являются не обязательными
  2065 #
  2066 # $_[0] - строка запроса
  2067 # $_[1] - ссылка на хэш запроса
  2068 #
  2069 {
  2070     my $query_string = shift;
  2071     my $query_hash = shift;
  2073     %{$query_hash} = (
  2074         "format"    =>  "txt",
  2075         "section"   =>  "",
  2076         "topic" =>  "",
  2077     );
  2079     if ($query_string =~ s/^([^:]*)://) {
  2080         $query_hash->{"format"} = $1 || "txt";
  2081     }
  2082     if ($query_string =~ s/\(([^(]*)\)$//) {
  2083         $query_hash->{"section"} = $1 || "";
  2084     }
  2085     $query_hash->{"topic"} = $query_string;
  2086 }
  2089 sub search_in_txt
  2090 #
  2091 # Выполнить поиск в текстовой базе 
  2092 # по известному запросу
  2093 # $_[0] -- ссылка на хэш запроса
  2094 # $_[1] -- ссылка на массив текстовых записей
  2095 # $_[2] -- ссылка на хэш массивов текстовых записей
  2096 # Результат:
  2097 #   найденная текстовая запись в заданном формате
  2098 #
  2099 {
  2100     my %Query = %{$_[0]};
  2101     my %MywiHASH = %{$_[2]};
  2103     my $topic = $Query{"topic"};
  2104     my $section = $Query{"section"};
  2105     my $result = "";
  2107     return join("\n",@{$MywiHASH{"$topic"}})."\n";
  2109     for my $l (@{$$_[2]{$topic}}) {
  2110 #    for my $l (@{$_[1]}) {
  2111         my $line = $l;
  2112         if (
  2113             ($section and $line =~ /^\s*\Q$topic\E\s*\($section*\)\s*-/ )
  2114             or (not $section and $line =~ /^\s*\Q$topic\E\s*(\([^)]*\)?)\s*-/) ) {
  2115             $line =~ s/^.* -//mg if ($Config{"short"});
  2116             $result .= "<para>$line</para>";
  2117         }
  2118     }
  2119     return $result;
  2120 }
  2123 sub add_to_log($$)
  2124 #
  2125 # Если в базе отсутствует информация по данной теме, 
  2126 # сделать предположение доступным способом
  2127 # и добавить его в базу
  2128 # или просто сделать отметку о необходимости 
  2129 # расширения базы
  2130 #
  2131 # Добавить запись в журнал
  2132 # $_[0] - запись (ссылка на хэш)
  2133 # $_[1] - имя файла-журнала
  2134 #
  2135 {
  2136     my $query = $_[0];
  2137     my $MyWiLog = $_[1];
  2139     open (MWF, ">>:utf8", $MyWiLog) or die "Can't open $MyWiLog for writing";
  2140     my $my_guess = mywi_guess($query);
  2141     print MWF "$my_guess\n";
  2142     close(MWF);
  2143 }
  2145 sub mywi_guess($)
  2146 # Сформировать исходную строку для журнала по заданному запросу
  2147 # Если секция принадлежит 0..9, в качестве основы для результирующего текста использовать whatis
  2148 # $_[0] - запись (ссылка на хэш)
  2149 # 
  2150 # Возвращает:
  2151 #   строку-предположение
  2152 {
  2153     my %query = %{$_[0]};
  2155     my $topic = $query{"topic"};
  2156     my $section = $query{"section"};
  2158     my $result = "$topic($section)";
  2159     if (!$section or $section =~ /^[1-9]$/)
  2160     {
  2161         # Запрос из категории 1-9
  2162         # Об этом может знать whatis
  2163         $result = `LANG=C whatis -- "$topic"`;
  2164         if ($result =~ /nothing appropriate/i) {
  2165             $result = $topic;
  2166             $result .= "($section)" if $section;
  2167         }
  2168         else {
  2169             1 while ($result =~ s/(\s+)-(\s+)/$1+$2/sg);
  2170             $result =~ s/\s+\(/(/;
  2171             chomp $result;
  2172         }
  2173     }   
  2174     return $result;
  2175 }
