lilalo
view l3-frontend @ 133:b9d00dd5596f
merge
| author | Igor Chubin <igor@chub.in> | 
|---|---|
| date | Fri Jul 04 17:51:09 2008 +0300 (2008-07-04) | 
| parents | 71bd999bcb04 | 
| children | 31ebdfe9797d | 
 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         $cline = "<span title='$prompt_hint'>".$cl->{"prompt"}."</span>"
   777                 ."<span onmouseover=\"myHint.show('".$cl->{time}."')\" onmouseout=\"myHint.hide()\">".$cl->{"cline"}."</span>";
   778         $cline =~ s/\n//;
   780         if ($cl->{"hint"}) {
   781 #            $cline = "<span title='$cl->{hint}' class='with_hint'>$cline</span>" ;
   782             $cline = "<span class='with_hint'>$cline</span>" ;
   783         } 
   784         else {
   785             $cline = "<span class='without_hint'>$cline</span>";
   786         }
   788         $this_day_result .= "<DIV class='fixed_div'><table cellpadding='0' cellspacing='0'><tr><td>\n<div class='cblock_$cl->{class}'>\n";
   789         $this_day_result .= "<div class='cline'>" . $cline ;      #cline
   790         $this_day_result .= "<span title='Код завершения ".$cl->{"err"}."'>\n"
   791                          .  "<img src='".$Config{frontend_ico_path}."/error.png'/>\n"
   792                          .  "</span>\n" if ($cl->{"err"} and not $cl->{tab_seq} and not $cl->{break});
   793         $this_day_result .= "<span title='Tab completion ".$cl->{tab_seq}."'>\n"
   794                          .  "<img src='".$Config{frontend_ico_path}."/tab.png'/>\n"
   795                          .  "</span>\n" if $cl->{tab_seq};
   796         $this_day_result .= "<span title='Ctrl-C pressed'>\n"
   797                          .  "<img src='".$Config{frontend_ico_path}."/break.png'/>\n"
   798                          .  "</span>\n" if ($cl->{break} and not $cl->{tab_seq});
   799         $this_day_result .= "</div>\n";                             #cline
   801 # OUTPUT
   802         my $last_command = $cl->{"last_command"};
   803         if (!( 
   804         $Config{"suppress_editors"} =~ /^y/i && grep ($_ eq $last_command, @{$Config{"editors"}}) ||
   805         $Config{"suppress_pagers"}  =~ /^y/i && grep ($_ eq $last_command, @{$Config{"pagers"}}) ||
   806         $Config{"suppress_terminal"}=~ /^y/i && grep ($_ eq $last_command, @{$Config{"terminal"}})
   807             )) {
   808             $this_day_result .= "<pre class='output'>\n" . $cl->{short_output} . "</pre>\n";
   809         }
   811 # DIFF
   812         $this_day_result .= "<pre class='diff'>".$cl->{"diff"}."</pre>"
   813             if ( $Config{"show_diffs"} =~ /^y/i && $cl->{"diff"});
   814 # SHOT
   815         $this_day_result .= "<img src='"
   816                 .$Config{l3shot_path}
   817                 .$cl->{"screenshot"}
   818                 ."' alt ='screenshot id ".$cl->{"screenshot"}
   819                 ."'/>"
   820             if ( $Config{"show_screenshots"} =~ /^y/i && $cl->{"screenshot"});
   822 #NOTES
   823         if ( $Config{"show_notes"} =~ /^y/i && $cl->{"note"}) {
   824             my $note=$cl->{"note"};
   825             $note =~ s/\n/<br\/>\n/msg;
   826             if (not $note =~ s@(http:[a-zA-Z.0-9/_?%-]*)@<a href='$1'>$1</a>@g) {
   827               $note =~ s@(www\.[a-zA-Z.0-9/_?%-]*)@<a href='$1'>$1</a>@g;
   828             };
   829             $this_day_result .= "<div class='note'>";
   830             $this_day_result .= "<div class='note_title'>".$cl->{note_title}."</div>" if $cl->{note_title};
   831             $this_day_result .= "<div class='note_text'>".$note."</div>";
   832             $this_day_result .= "</div>\n";
   833         }
   835         # Вывод очередной команды окончен
   836         $this_day_result .= "</div>\n";                     # cblock
   837         $this_day_result .= "</td></tr></table></DIV>\n"
   838                          .  "</div>\n";                     # command
   839     }
   840     last: {
   841         $prev_unix_time=$first_command_of_the_day_unix_time;
   842         $first_command_of_the_day_unix_time = $cl->{time};
   843         $human_readable_time = strftime "%D", localtime($prev_unix_time);
   845         $result .= "<h3 id='day_on_sec_$prev_unix_time'>".$Day_Name[$last_wday]." ($human_readable_time)</h3>";
   847         for my $entry_class (keys %new_entries_of) {
   848             my $table_caption = "Таблица ".$table_number++.".".$Day_Name[$last_wday]
   849                               . ". Новые ".$new_entries_of{$entry_class};
   850             my $new_commands_section = make_new_entries_table(
   851                                         $table_caption, 
   852                                         $entry_class=~/[0-9]+\s+(.*)/, 
   853                                         \@known_commands);
   854         }
   855         @known_commands = keys %frequency_of_command;
   856         $result .= $this_day_result;
   857    }
   859     return ($result, collapse_list (\@toc));
   861 }
   863 #############
   864 # make_new_entries_table
   865 #
   866 # Напечатать таблицу неизвестных команд
   867 #
   868 # In:       $_[0]       table_caption
   869 #           $_[1]       entries_class
   870 #           @_[2..]     known_commands
   871 # Out:
   873 sub make_new_entries_table
   874 {
   875     my $table_caption;
   876     my $entries_class = shift;
   877     my @known_commands = @{$_[0]};
   878     my $result = "";
   880     my %count;
   881     my @new_commands = ();
   882     for my $c (keys %frequency_of_command, @known_commands) {
   883         $count{$c}++
   884     }
   885     for my $c (keys %frequency_of_command) {
   886         push @new_commands, $c if $count{$c} != 2;
   887     }
   889     my $new_commands_section;
   890     if (@new_commands){
   891         my $hint;
   892         for my $c (reverse sort { $frequency_of_command{$a} <=> $frequency_of_command{$b} } @new_commands) {
   893                 $hint = make_comment($c);
   894                 next unless $hint;
   895                 my ($command, $hint) = $hint =~ m/(.*?) \s*- \s*(.*)/;
   896                 next unless $command =~ s/\($entries_class\)//i;
   897                 $new_commands_section .= "<tr><td valign='top'>$command</td><td>$hint</td></tr>";
   898         }
   899     }
   900     if ($new_commands_section) {
   901         $result .= "<table class='new_commands_table' width='700' cellspacing='0' cellpadding='0'>"
   902                 .  "<tr class='new_commands_caption'>"
   903                 .  "<td colspan='2' align='right'>$table_caption</td>"
   904                 .  "</tr>"
   905                 .  "<tr class='new_commands_header'>"
   906                 .  "<td width=100>Команда</td><td width=600>Описание</td>"
   907                 .  "</tr>"
   908                 .  $new_commands_section 
   909                 .  "</table>"
   910     }
   911     return $result;
   912 }
   914 #############
   915 # minutes_passed
   916 #
   917 #
   918 #
   919 # In:       $_[0]       seconds_since_last_command
   920 # Out:                  "minutes passed" text
   922 sub minutes_passed
   923 {
   924         my $seconds_since_last_command = shift;
   925         my $result = "";
   926         if ($seconds_since_last_command > 7200) {
   927             my $hours_passed =  int($seconds_since_last_command/3600);
   928             my $passed_word  = $hours_passed % 10 == 1 ? "прошла"
   929                                                          : "прошло";
   930             my $hours_word   = $hours_passed % 10 == 1 ?   "часа":
   931                                                            "часов";
   932             $result .= "<div class='much_time_passed'>"
   933                     .  $passed_word." >".$hours_passed." ".$hours_word
   934                     .  "</div>\n";
   935         }
   936         elsif ($seconds_since_last_command > 600) {
   937             my $minutes_passed =  int($seconds_since_last_command/60);
   940             my $passed_word  = $minutes_passed % 100 > 10 
   941                             && $minutes_passed % 100 < 20 ? "прошло"
   942                              : $minutes_passed % 10 == 1  ? "прошла"
   943                                                           : "прошло";
   945             my $minutes_word = $minutes_passed % 100 > 10 
   946                             && $minutes_passed % 100 < 20 ? "минут" :
   947                                $minutes_passed % 10 == 1 ? "минута":
   948                                $minutes_passed % 10 == 0 ? "минут" :
   949                                $minutes_passed % 10  > 4 ? "минут" :
   950                                                            "минуты";
   952             if ($seconds_since_last_command < 1800) {
   953                 $result .= "<div class='time_passed'>"
   954                         .  $passed_word." ".$minutes_passed." ".$minutes_word
   955                         .  "</div>\n";
   956             }
   957             else {
   958                 $result .= "<div class='much_time_passed'>"
   959                         .  $passed_word." ".$minutes_passed." ".$minutes_word
   960                         .  "</div>\n";
   961             }
   962         }
   963         return $result;
   964 }
   966 #############
   967 # print_all_txt
   968 #
   969 # Вывести журнал в текстовом формате
   970 #
   971 # In:       $_[0]       output_filename
   972 # Out:
   974 sub print_command_lines_txt
   975 {
   977     my $output_filename=$_[0];
   978     my $note_number=0;
   980     my $result = q();
   981     my $this_day_resut = q();
   983     my $cl;
   984     my $last_tty="";
   985     my $last_session="";
   986     my $last_day=q();
   987     my $last_wday=q();
   988     my $in_range=0;
   990     my $current_command=0;
   992     my $cursor_position = 0;
   995     if ($Config{filter}) {
   996         # Инициализация фильтра
   997         for (split /&/,$Config{filter}) {
   998             my ($var, $val) = split /=/;
   999             $filter{$var} = $val || "";
  1000         }
  1001     }
  1004 COMMAND_LINE:
  1005     for my $k (@Command_Lines_Index) {
  1007         my $cl=$Command_Lines[$Command_Lines_Index[$current_command++]];
  1008         next unless $cl;
  1011 # Пропускаем строки, которые противоречат фильтру
  1012 # Если у нас недостаточно информации о том, подходит строка под  фильтр или нет, 
  1013 # мы её выводим
  1015         for my $filter_key (keys %filter) {
  1016             next COMMAND_LINE 
  1017                 if defined($cl->{local_session_id})
  1018                 && defined($Sessions{$cl->{local_session_id}}->{$filter_key})
  1019                 && $Sessions{$cl->{local_session_id}}->{$filter_key} ne $filter{$filter_key};
  1020         }
  1022 # Пропускаем строки, выходящие за границу "signature",
  1023 # при условии, что границы указаны
  1024 # Пропускаем неправильные/прерванные/другие команды
  1025         if ($Config{"from"} && $cl->{"cline"} =~ /$Config{"signature"}\s*$Config{"from"}/) {
  1026             $in_range=1;
  1027             next;
  1028         }
  1029         if ($Config{"to"} && $cl->{"cline"} =~ /$Config{"signature"}\s*$Config{"to"}/) {
  1030             $in_range=0;
  1031             next;
  1032         }
  1033         next    if ($Config{"from"} && $Config{"to"}   && !$in_range) 
  1034                 || ($Config{"skip_empty"} =~ /^y/i     && $cl->{"cline"} =~ /^\s*$/ )
  1035                 || ($Config{"skip_wrong"} =~ /^y/i     && $cl->{"err"} != 0)
  1036                 || ($Config{"skip_interrupted"} =~ /^y/i && $cl->{"err"} == 130);
  1039 #
  1040 ##
  1041 ## Начинается собственно вывод
  1042 ##
  1043 #
  1045 ### Сначала обрабатываем границы разделов
  1046 ### Если тип команды "note", это граница
  1048         if ($cl->{class} eq "note") {
  1049             $this_day_result .= " === ".$cl->{note_title}." === \n" if $cl->{note_title};
  1050             $this_day_result .= $cl->{note}."\n";
  1051             next;
  1052         }
  1054         my ($sec,$min,$hour,$day,$mon,$year,$wday,$yday,$isdst) = localtime($cl->{time});
  1056         # Добавляем спереди 0 для удобочитаемости
  1057         $min  = "0".$min  if $min  =~ /^.$/;
  1058         $hour = "0".$hour if $hour =~ /^.$/;
  1059         $sec  = "0".$sec  if $sec  =~ /^.$/;
  1061         $class=$cl->{"class"};
  1063 # DAY CHANGE
  1064         if ( $last_day ne $day) {
  1065             if ($last_day) {
  1066                 $result .= "== ".$Day_Name[$last_wday]." == \n";
  1067                 $result .= $this_day_result;
  1068             }
  1069             $last_day   = $day;
  1070             $last_wday  = $wday;
  1071             $this_day_result = q();
  1072         }
  1074 # CONSOLE CHANGE
  1075         if ($cl->{"tty"} && $last_tty ne $cl->{"tty"} && 0) {
  1076             my $tty = $cl->{"tty"};
  1077             $this_day_result .= "         #l3: ------- другая консоль ----\n";
  1078             $last_tty=$cl->{"tty"};
  1079         }
  1081 # Session change
  1082         if ( $last_session ne $cl->{"local_session_id"}) {
  1083             $this_day_result .= "# ------------------------------------------------------------"
  1084                              .  "  l3: local_session_id=".$cl->{"local_session_id"}
  1085                              .  " ---------------------------------- \n";
  1086             $last_session=$cl->{"local_session_id"};
  1087         }
  1089 # TIME
  1090         my @nl_counter = split (/\n/, $result);
  1091         $cursor_position=length($result) - @nl_counter;
  1093         if ($Config{"show_time"} =~ /^y/i) {
  1094             $this_day_result .= "$hour:$min:$sec" 
  1095         }
  1097 # COMMAND
  1098         $this_day_result .= " ".$cl->{"prompt"}.$cl->{"cline"}."\n";
  1099         if ($cl->{"err"}) {
  1100             $this_day_result .= "         #l3: err=".$cl->{'err'}."\n";
  1101         }
  1103 # OUTPUT
  1104         my $last_command = $cl->{"last_command"};
  1105         if (!( 
  1106         $Config{"suppress_editors"} =~ /^y/i && grep ($_ eq $last_command, @{$Config{"editors"}}) ||
  1107         $Config{"suppress_pagers"}  =~ /^y/i && grep ($_ eq $last_command, @{$Config{"pagers"}}) ||
  1108         $Config{"suppress_terminal"}=~ /^y/i && grep ($_ eq $last_command, @{$Config{"terminal"}})
  1109             )) {
  1110             my $output = $cl->{short_output};
  1111             if ($output) {
  1112                  $output =~ s/^/         |/mg;
  1113             }
  1114             $this_day_result .= $output;
  1115         }
  1117 # DIFF
  1118         if ( $Config{"show_diffs"} =~ /^y/i && $cl->{"diff"}) {
  1119             my $diff = $cl->{"diff"};
  1120             $diff =~ s/^/         |/mg;
  1121             $this_day_result .= $diff;
  1122         };
  1123 # SHOT
  1124         if ($Config{"show_screenshots"} =~ /^y/i && $cl->{"screenshot"}) {
  1125             $this_day_result .= "         #l3: screenshot=".$cl->{'screenshot'}."\n";
  1126         }
  1128 #NOTES
  1129         if ( $Config{"show_notes"} =~ /^y/i && $cl->{"note"}) {
  1130             my $note=$cl->{"note"};
  1131             $note =~ s/\n/\n#^/msg;
  1132             $this_day_result .= "#^ == ".$cl->{note_title}." ==\n" if $cl->{note_title};
  1133             $this_day_result .= "#^ ".$note."\n";
  1134         }
  1136     }
  1137     last: {
  1138         $result .= "== ".$Day_Name[$last_wday]." == \n";
  1139         $result .= $this_day_result;
  1140    }
  1142    return $result;
  1146 }
  1148 #############
  1149 # print_edit_all_html
  1150 #
  1151 # Вывести страницу с текстовым представлением журнала для редактирования
  1152 #
  1153 # In:       $_[0]       output_filename
  1154 # Out:
  1156 sub print_edit_all_html
  1157 {
  1158     my $output_filename= shift;
  1159     my $result;
  1160     my $cursor_position = 0;
  1162     $result = print_command_lines_txt;
  1163     my $title = ">Журнал лабораторных работ. Правка";
  1165     $result = 
  1166                "<html>"
  1167                 ."<head>"
  1168                 ."<meta content='text/html; charset=utf-8' http-equiv='Content-Type' />"
  1169                 ."<link rel='stylesheet' href='$Config{frontend_css}' type='text/css'/>"
  1170                 ."<title>$title</title>"
  1171                 ."</head>"
  1172               ."<script>"
  1173               .$SetCursorPosition_JS
  1174               ."</script>"
  1175               ."<body onLoad='setCursorPosition(document.all.mytextarea, $cursor_position, $cursor_position+10)'>"
  1176               ."<h1>Журнал лабораторных работ. Правка</h1>"
  1177               ."<form>"
  1178               ."<textarea rows='30' cols='100' wrap='off' id='mytextarea'>$result</textarea>"
  1179               ."<br/><input type='submit' value='Сохранить' label='label'/>"
  1180               ."</form>"
  1181               ."<p>Внимательно правим, потом сохраняем</p>"
  1182               ."<p>Строки, начинающиеся символами #l3: можно трогать, только если точно знаешь, что делаешь</p>"
  1183               ."</body>"
  1184               ."</html>";
  1186     if ($output_filename eq "-") {
  1187         print $result;
  1188     }
  1189     else {
  1190         open(OUT, ">", $output_filename)
  1191             or die "Can't open $output_filename for writing\n";
  1192         binmode ":utf8";
  1193         print OUT "$result";
  1194         close(OUT);
  1195     }
  1196 }
  1198 #############
  1199 # print_all_txt
  1200 #
  1201 # Вывести страницу с текстовым представлением журнала для редактирования
  1202 #
  1203 # In:       $_[0]       output_filename
  1204 # Out:
  1206 sub print_all_txt
  1207 {
  1208     my $result;
  1210     $result = print_command_lines_txt;
  1212     $result =~ s/>/>/g;
  1213     $result =~ s/</</g;
  1214     $result =~ s/&/&/g;
  1216     if ($output_filename eq "-") {
  1217         print $result;
  1218     }
  1219     else {
  1220         open(OUT, ">:utf8", $output_filename)
  1221             or die "Can't open $output_filename for writing\n";
  1222         print OUT "$result";
  1223         close(OUT);
  1224     }
  1225 }
  1228 #############
  1229 # print_all_html
  1230 #
  1231 #
  1232 #
  1233 # In:       $_[0]       output_filename
  1234 # Out:
  1237 sub print_all_html
  1238 {
  1239     my $output_filename=$_[0];
  1241     my $result;
  1242     my ($command_lines,$toc)  = print_command_lines_html;
  1243     my $files_section         = print_files_html;
  1245     $result = $debug_output;
  1246     $result .= print_header_html($toc);
  1249 #    $result.= join " <br/>", keys %Sessions;
  1250 #    for my $sess (keys %Sessions) {
  1251 #            $result .= join " ", keys (%{$Sessions{$sess}});
  1252 #            $result .= "<br/>";
  1253 #    }
  1255     $result.= "<h2 id='log'>Журнал</h2>"       . $command_lines;
  1256     $result.= "<h2 id='files'>Файлы</h2>"      . $files_section if $files_section;
  1257     $result.= "<h2 id='stat'>Статистика</h2>"  . print_stat_html;
  1258     $result.= "<h2 id='help'>Справка</h2>"     . $Html_Help . "<br/>"; 
  1259     $result.= "<h2 id='about'>О программе</h2>". $Html_About. "<br/>"; 
  1260     $result.= print_footer_html;
  1262     if ($output_filename eq "-") {
  1263         binmode STDOUT, ":utf8";
  1264         print $result;
  1265     }
  1266     else {
  1267         open(OUT, ">:utf8", $output_filename)
  1268             or die "Can't open $output_filename for writing\n";
  1269         print OUT $result;
  1270         close(OUT);
  1271     }
  1272 }
  1274 #############
  1275 # print_header_html
  1276 #
  1277 #
  1278 #
  1279 # In:   $_[0]       Содержание
  1280 # Out:              Распечатанный заголовок
  1282 sub print_header_html
  1283 {
  1284     my $toc = $_[0];
  1285     my $course_name = $Config{"course-name"};
  1286     my $course_code = $Config{"course-code"};
  1287     my $course_date = $Config{"course-date"};
  1288     my $course_center = $Config{"course-center"};
  1289     my $course_trainer = $Config{"course-trainer"};
  1290     my $course_student = $Config{"course-student"};
  1292     my $title    = "Журнал лабораторных работ";
  1293     $title      .= " -- ".$course_student if $course_student;
  1294     if ($course_date) {
  1295         $title  .= " -- ".$course_date; 
  1296         $title  .= $course_code ? "/".$course_code 
  1297                                 : "";
  1298     }
  1299     else {
  1300         $title  .= " -- ".$course_code if $course_code;
  1301     }
  1303     # Управляющая форма
  1304     my $control_form .= "<div class='visibility_form' title='Выберите какие элементы должны быть показаны в журнале'>"
  1305                      .  "<span class='header'>Видимые элементы</span>"
  1306                      .  "<span class='window_controls'><a href='' onclick='' title='свернуть форму управления'>_</a> <a href='' onclick='' title='закрыть форму управления'>x</a></span>"
  1307                      .  "<div><form>\n";
  1308     for my $element (sort keys %Elements_Visibility)
  1309     {
  1310         my ($skip, @e) = split /\s+/, $element;
  1311         my $showhide = join "", map { "ShowHide('$_');" } @e ;
  1312         $control_form .= "<div><input type='checkbox' name='$e[0]' onclick=\"$showhide\" checked>".
  1313                 $Elements_Visibility{$element}.
  1314                 "</input></div>";
  1315     }
  1316     $control_form .= "</form>\n"
  1317                   .  "</div>\n";
  1320     # Управляющая форма отключена
  1321     # Она слишком сильно мешает, нужно что-то переделать
  1322     $control_form = "";
  1324     my $tigra_hints_array=tigra_hints_generate;
  1326     my $result;
  1327     $result = <<HEADER;
  1328     <html>
  1329     <head>
  1330     <meta content='text/html; charset=utf-8' http-equiv='Content-Type' />
  1331     <link rel='stylesheet' href='$Config{frontend_css}' type='text/css'/>
  1332     <title>$title</title>
  1333     </head>
  1334     <body>
  1335     <!--<script>
  1336     $Html_JavaScript
  1337     </script>-->
  1339 <!-- vvv Tigra Hints vvv -->
  1340 <script language="JavaScript" src="/tigra/hints.js"></script>
  1341 <!--<script language="JavaScript" src="/tigra/hints_cfg.js"></script>-->
  1342 <script>$tigra_hints_array</script>
  1343 <style>
  1344 /* a class for all Tigra Hints boxes, TD object */
  1345     .hintsClass
  1346         {text-align: left; font-size:80%; font-family: Verdana, Arial, Helvetica; background-color:#ffffee; padding: 0px 0px 0px 0px;}
  1347 /* this class is used by Tigra Hints wrappers */
  1348     .row
  1349         {background: white;}
  1352     .bl2 {border: 1px solid #e68200; background:url(/tigra/block/bl2.gif) 0 100% no-repeat; text-align:left}
  1353     .bl {background:url(/tigra/block/bl2.gif) 0 100% no-repeat; text-align:left}
  1354     .br {background:url(/tigra/block/br2.gif) 100% 100% no-repeat}
  1355     .tl {background:url(/tigra/block/tl2.gif) 0 0 no-repeat}
  1356     .tr {background:url(/tigra/block/tr2.gif) 100% 0 no-repeat; padding:10px}
  1357     .tr2 {background:url(/tigra/block/tr2.gif) 100% 0 no-repeat}
  1358     .t {background:url(/tigra/block/dot2.gif) 0 0 repeat-x}
  1359     .b {background:url(/tigra/block/dot2.gif) 0 100% repeat-x}
  1360     .l {background:url(/tigra/block/dot2.gif) 0 0 repeat-y}
  1361     .r {background:url(/tigra/block/dot2.gif) 100% 0 repeat-y}
  1364 </style>
  1365 <!-- ^^^ Tigra Hints ^^^ -->
  1367 <!--
  1368     .bl2 {border: 1px solid #e68200; background:url(/tigra/block/bl2.gif) 0 100% no-repeat; width:20em; text-align:center}
  1369     .bl {background:url(/tigra/block/bl2.gif) 0 100% no-repeat; width:20em; text-align:center}
  1370     .br {background:url(/tigra/block/br2.gif) 100% 100% no-repeat}
  1371     .tl {background:url(/tigra/block/tl2.gif) 0 0 no-repeat}
  1372     .tr {background:url(/tigra/block/tr2.gif) 100% 0 no-repeat; padding:10px}
  1373     .tr2 {background:url(/tigra/block/tr2.gif) 100% 0 no-repeat}
  1374     .t {background:url(/tigra/block/dot2.gif) 0 0 repeat-x; width:20em}
  1375     .b {background:url(/tigra/block/dot2.gif) 0 100% repeat-x}
  1376     .l {background:url(/tigra/block/dot2.gif) 0 0 repeat-y}
  1377     .r {background:url(/tigra/block/dot2.gif) 100% 0 repeat-y}
  1378 -->
  1381     <div class='edit_link'>
  1382     [ <a href='?action=edit&$filter_url'>править</a> ]
  1383     </div>
  1384     <h1 onmouseover="myHint.show('1')" onmouseout="myHint.hide()" class='lined_header'>Журнал лабораторных работ</h1>
  1385 HEADER
  1386     if (    $course_student 
  1387             || $course_trainer 
  1388             || $course_name 
  1389             || $course_code 
  1390             || $course_date 
  1391             || $course_center) {
  1392             $result .= "<p>";
  1393             $result .= "Выполнил $course_student<br/>"  if $course_student;
  1394             $result .= "Проверил $course_trainer <br/>" if $course_trainer;
  1395             $result .= "Курс "                          if $course_name 
  1396                                                             || $course_code 
  1397                                                             || $course_date;
  1398             $result .= "$course_name "                  if $course_name;
  1399             $result .= "($course_code)"                 if $course_code;
  1400             $result .= ", $course_date<br/>"            if $course_date;
  1401             $result .= "Учебный центр $course_center <br/>" if $course_center;
  1402             $result .= "Фильтр ".join(" ", map("$filter{$_}=$_", keys %filter))."<br/>" if %filter;
  1403             $result .= "</p>";
  1404     }
  1406     $result .= <<HEADER;
  1407     <table width='100%'>
  1408     <tr>
  1409     <td width='*'>
  1411     <table border=0 id='toc' class='toc'>
  1412     <tr>
  1413     <td>
  1414     <div class='toc_title'>Содержание</div>
  1415     <ul>
  1416         <li><a href='#log'>Журнал</a></li>
  1417         <ul>$toc</ul>
  1418         <li><a href='#files'>Файлы</a></li>
  1419         <li><a href='#stat'>Статистика</a></li>
  1420         <li><a href='#help'>Справка</a></li>
  1421         <li><a href='#about'>О программе</a></li>
  1422     </ul>
  1423     </td>
  1424     </tr>
  1425     </table>
  1427     </td>
  1428     <td valign='top' width=200>$control_form</td>
  1429     </tr>
  1430     </table>
  1431 HEADER
  1433     return $result;
  1434 }
  1437 #############
  1438 # print_footer_html
  1439 #
  1440 #
  1441 #
  1442 #
  1443 #
  1445 sub print_footer_html
  1446 {
  1447     return "</body>\n</html>\n";
  1448 }
  1453 #############
  1454 # print_stat_html
  1455 #
  1456 #
  1457 #
  1458 # In:
  1459 # Out:
  1461 sub print_stat_html
  1462 {
  1463     %StatNames = (
  1464         FirstCommand        => "Время первой команды журнала",
  1465         LastCommand         => "Время последней команды журнала",
  1466         TotalCommands       => "Количество командных строк в журнале",
  1467         ErrorsPercentage    => "Процент команд с ненулевым кодом завершения, %",
  1468         MistypesPercentage  => "Процент синтаксически неверно набранных команд, %",
  1469         TotalTime           => "Суммарное время работы с терминалом <sup><font size='-2'>*</font></sup>, час",
  1470         CommandsPerTime     => "Количество командных строк в единицу времени, команда/мин",
  1471         CommandsFrequency   => "Частота использования команд",
  1472         RareCommands        => "Частота использования этих команд < 0.5%",
  1473     );
  1474     @StatOrder = (
  1475         FirstCommand,
  1476         LastCommand,
  1477         TotalCommands,
  1478         ErrorsPercentage,
  1479         MistypesPercentage,
  1480         TotalTime,
  1481         CommandsPerTime,
  1482         CommandsFrequency,
  1483         RareCommands,
  1484     );
  1486     # Подготовка статистики к выводу
  1487     # Некоторые значения пересчитываются!
  1488     # Дальше их лучше уже не использовать!!!
  1490     my %CommandsFrequency = %frequency_of_command;
  1492     $Stat{TotalTime} ||= 0;
  1493     my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($Stat{FirstCommand} || 0);
  1494     $Stat{FirstCommand} = sprintf "%02i:%02i:%02i %04i-%2i-%2i", $hour, $min, $sec,  $year+1900, $mon+1, $mday;
  1495     ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($Stat{LastCommand} || 0);
  1496     $Stat{LastCommand} = sprintf "%02i:%02i:%02i %04i-%2i-%2i", $hour, $min, $sec,  $year+1900, $mon+1, $mday;
  1497     if ($Stat{TotalCommands}) {
  1498         $Stat{ErrorsPercentage} = sprintf "%5.2f", $Stat{ErrorCommands}*100/$Stat{TotalCommands};
  1499         $Stat{MistypesPercentage} = sprintf "%5.2f", $Stat{MistypedCommands}*100/$Stat{TotalCommands};
  1500     }
  1501     $Stat{CommandsPerTime} = sprintf "%5.2f", $Stat{TotalCommands}*60/$Stat{TotalTime}
  1502         if $Stat{TotalTime};
  1503     $Stat{TotalTime} = sprintf "%5.2f", $Stat{TotalTime}/60/60;
  1505     my $total_commands=0;
  1506     for $command (keys %CommandsFrequency){
  1507         $total_commands += $CommandsFrequency{$command};
  1508     }
  1509     if ($total_commands) {
  1510         for $command (reverse sort {$CommandsFrequency{$a} <=> $CommandsFrequency{$b}} keys %CommandsFrequency){
  1511             my $command_html;
  1512             my $percentage = sprintf "%5.2f",$CommandsFrequency{$command}*100/$total_commands;
  1513             if ($percentage < 0.5) {
  1514                 my $hint = make_comment($command);
  1515                 $command_html = "$command";
  1516                 $command_html = "<span title='$hint' class='with_hint'>$command_html</span>" if $hint;
  1517                 $command_html = "<span class='without_hint'>$command_html</span>" if not $hint;
  1518                 my $command_html = "<tt>$command_html</tt>";
  1519                 $Stat{RareCommands} .= $command_html."<sub><font size='-2'>".$CommandsFrequency{$command}."</font></sub> , ";
  1520             }
  1521             else {
  1522                 my $hint = make_comment($command);
  1523                 $command_html = "$command";
  1524                 $command_html = "<span title='$hint' class='with_hint'>$command_html</span>" if $hint;
  1525                 $command_html = "<span class='without_hint'>$command_html</span>" if not $hint;
  1526                 my $command_html = "<tt>$command_html</tt>";
  1527                 $percentage = sprintf "%5.2f",$percentage;
  1528                 $Stat{CommandsFrequency} .= "<tr><td>".$command_html."</td><td>".$CommandsFrequency{$command}."</td>".
  1529                     "<td>|".("="x int($CommandsFrequency{$command}*100/$total_commands))."| $percentage%</td></tr>";
  1530             }
  1531         }
  1532         $Stat{CommandsFrequency} = "<table>".$Stat{CommandsFrequency}."</table>";
  1533         $Stat{RareCommands} =~ s/, $// if $Stat{RareCommands};
  1534     }
  1536     my $result = q();
  1537     for my $stat (@StatOrder) {
  1538         next unless $Stat{"$stat"};
  1539         $result .= "<tr valign='top'><td width='300'>".$StatNames{"$stat"}."</td><td>".$Stat{"$stat"}."</td></tr>"
  1540     }
  1541     $result  = "<table>$result</table>"
  1542              . "<font size='-2'>____<br/>*) Интервалы неактивности длительностью "
  1543              .  ($Config{stat_inactivity_interval}/60)
  1544              . " минут и более не учитываются</font></br>";
  1546     return $result;
  1547 }
  1550 sub collapse_list($)
  1551 {
  1552     my $res = "";
  1553     for my $elem (@{$_[0]}) {
  1554         if (ref $elem eq "ARRAY") {
  1555             $res .= "<ul>".collapse_list($elem)."</ul>";
  1556         }
  1557         else
  1558         {
  1559             $res .= "<li>".$elem."</li>";
  1560         }
  1561     }
  1562     return $res;
  1563 }
  1566 sub print_files_html
  1567 {
  1568     my $result = qq(); 
  1569     my @toc;
  1570     for my $file (sort keys %Files) {
  1571           my $div_id = "file:$file";
  1572           $div_id =~ s@/@_@g;
  1573           push @toc, "<a href='#$div_id'>$file</a>";
  1574           $result .= "<div class='filename' id='$div_id'>".$file."</div>\n"
  1575                   .  "<div class='file_navigation'><a href='#command:".$Files{$file}->{source_command_id}."'>".">"."</a></div>"
  1576                   .  "<div class='filedata'><pre>".$Files{$file}->{content}."</pre></div>";
  1577     }
  1578     if ($result) {
  1579         return "<div class='files_toc'>".collapse_list(\@toc)."</div>".$result;
  1580     } 
  1581     else {
  1582         return "";
  1583     }
  1584 }
  1587 sub init_variables
  1588 {
  1589 $Html_Help = <<HELP;
  1590     Для того чтобы использовать LiLaLo, не нужно знать ничего особенного:
  1591     всё происходит само собой.
  1592     Однако, чтобы ведение и последующее использование журналов
  1593     было как можно более эффективным, желательно иметь в виду следующее:
  1594     <ol>
  1595     <li><p> 
  1596     В журнал автоматически попадают все команды, данные в любом терминале системы.
  1597     </p></li>
  1598     <li><p>
  1599     Для того чтобы убедиться, что журнал на текущем терминале ведётся, 
  1600     и команды записываются, дайте команду w.
  1601     В поле WHAT, соответствующем текущему терминалу, 
  1602     должна быть указана программа script.
  1603     </p></li>
  1604     <li><p>
  1605     Команды, при наборе которых были допущены синтаксические ошибки, 
  1606     выводятся перечёркнутым текстом:
  1607 <table>
  1608 <tr class='command'>
  1609 <td class='script'>
  1610 <pre class='_mistyped_cline'>
  1611 \$ l s-l</pre>
  1612 <pre class='_mistyped_output'>bash: l: command not found
  1613 </pre>
  1614 </td>
  1615 </tr>
  1616 </table>
  1617 <br/>
  1618     </p></li>
  1619     <li><p>
  1620     Если код завершения команды равен нулю, 
  1621     команда была выполнена без ошибок.
  1622     Команды, код завершения которых отличен от нуля, выделяются цветом.
  1623 <table>
  1624 <tr class='command'>
  1625 <td class='script'>
  1626 <pre class='_wrong_cline'>
  1627 \$ test 5 -lt 4</pre>
  1628 </pre>
  1629 </td>
  1630 </tr>
  1631 </table>
  1632     Обратите внимание на то, что код завершения команды может быть отличен от нуля
  1633     не только в тех случаях, когда команда была выполнена с ошибкой.
  1634     Многие команды используют код завершения, например, для того чтобы показать результаты проверки
  1635 <br/>
  1636     </p></li>
  1637     <li><p>
  1638     Команды, ход выполнения которых был прерван пользователем, выделяются цветом.
  1639 <table>
  1640 <tr class='command'>
  1641 <td class='script'>
  1642 <pre class='_interrupted_cline'>
  1643 \$ find / -name abc</pre>
  1644 <pre class='interrupted_output'>find: /home/devi-orig/.gnome2: Keine Berechtigung
  1645 find: /home/devi-orig/.gnome2_private: Keine Berechtigung
  1646 find: /home/devi-orig/.nautilus/metafiles: Keine Berechtigung
  1647 find: /home/devi-orig/.metacity: Keine Berechtigung
  1648 find: /home/devi-orig/.inkscape: Keine Berechtigung
  1649 ^C
  1650 </pre>
  1651 </td>
  1652 </tr>
  1653 </table>
  1654 <br/>
  1655     </p></li>
  1656     <li><p>
  1657     Команды, выполненные с привилегиями суперпользователя,
  1658     выделяются слева красной чертой.
  1659 <table>
  1660 <tr class='command'>
  1661 <td class='script'>
  1662 <pre class='_root_cline'>
  1663 # id</pre>
  1664 <pre class='_root_output'>
  1665 uid=0(root) gid=0(root) Gruppen=0(root)
  1666 </pre>
  1667 </td>
  1668 </tr>
  1669 </table>
  1670     <br/>
  1671     </p></li>
  1672     <li><p>
  1673     Изменения, внесённые в текстовый файл с помощью редактора, 
  1674     запоминаются и показываются в журнале в формате ed.
  1675     Строки, начинающиеся символом "<", удалены, а строки,
  1676     начинающиеся символом ">" -- добавлены.
  1677 <table>
  1678 <tr class='command'>
  1679 <td class='script'>
  1680 <pre class='cline'>
  1681 \$ vi ~/.bashrc</pre>
  1682 <table><tr><td width='5'/><td class='diff'><pre>2a3,5
  1683 >    if [ -f /usr/local/etc/bash_completion ]; then
  1684 >         . /usr/local/etc/bash_completion
  1685 >        fi
  1686 </pre></td></tr></table></td>
  1687 </tr>
  1688 </table>
  1689     <br/>
  1690     </p></li>
  1691     <li><p>
  1692     Для того чтобы изменить файл в соответствии с показанными в диффшоте
  1693     изменениями, можно воспользоваться командой patch.
  1694     Нужно скопировать изменения, запустить программу patch, указав в
  1695     качестве её аргумента файл, к которому применяются изменения,
  1696     и всавить скопированный текст:
  1697 <table>
  1698 <tr class='command'>
  1699 <td class='script'>
  1700 <pre class='cline'>
  1701 \$ patch ~/.bashrc</pre>
  1702 </td>
  1703 </tr>
  1704 </table>
  1705     В данном случае изменения применяются к файлу ~/.bashrc
  1706     </p></li>
  1707     <li><p>
  1708     Для того чтобы получить краткую справочную информацию о команде, 
  1709     нужно подвести к ней мышь. Во всплывающей подсказке появится краткое
  1710     описание команды.
  1711     </p>
  1712     <p>
  1713     Если справочная информация о команде есть, 
  1714     команда выделяется голубым фоном, например: <span class="with_hint" title="главный текстовый редактор Unix">vi</span>.
  1715     Если справочная информация отсутствует,
  1716     команда выделяется розовым фоном, например: <span class="without_hint">notepad.exe</span>.
  1717     Справочная информация может отсутствовать в том случае, 
  1718     если (1) команда введена неверно; (2) если распознавание команды LiLaLo выполнено неверно;
  1719     (3) если информация о команде неизвестна LiLaLo.
  1720     Последнее возможно для редких команд.
  1721     </p></li>
  1722     <li><p>
  1723     Большие, в особенности многострочные, всплывающие подсказки лучше 
  1724     всего показываются браузерами KDE Konqueror, Apple Safari и Microsoft Internet Explorer.
  1725     В браузерах Mozilla и Firefox они отображаются не полностью, 
  1726     а вместо перевода строки выводится специальный символ.
  1727     </p></li>
  1728     <li><p>
  1729     Время ввода команды, показанное в журнале, соответствует времени 
  1730     <i>начала ввода командной строки</i>, которое равно тому моменту, 
  1731     когда на терминале появилось приглашение интерпретатора
  1732     </p></li>
  1733     <li><p>
  1734     Имя терминала, на котором была введена команда, показано в специальном блоке.
  1735     Этот блок показывается только в том случае, если терминал
  1736     текущей команды отличается от терминала предыдущей.
  1737     </p></li>
  1738     <li><p>
  1739     Вывод не интересующих вас в настоящий момент элементов журнала,
  1740     таких как время, имя терминала и других, можно отключить.
  1741     Для этого нужно воспользоваться <a href='#visibility_form'>формой управления журналом</a>
  1742     вверху страницы.
  1743     </p></li>
  1744     <li><p>
  1745     Небольшие комментарии к командам можно вставлять прямо из командной строки.
  1746     Комментарий вводится прямо в командную строку, после символов #^ или #v.
  1747     Символы ^ и v показывают направление выбора команды, к которой относится комментарий:
  1748     ^ - к предыдущей, v - к следующей.
  1749     Например, если в командной строке было введено:
  1750 <pre class='cline'>
  1751 \$ whoami
  1752 </pre>
  1753 <pre class='output'>
  1754 user
  1755 </pre>
  1756 <pre class='cline'>
  1757 \$ #^ Интересно, кто я?
  1758 </pre>
  1759     в журнале это будет выглядеть так:
  1761 <pre class='cline'>
  1762 \$ whoami
  1763 </pre>
  1764 <pre class='output'>
  1765 user
  1766 </pre>
  1767 <table class='note'><tr><td width='100%' class='note_text'>
  1768 <tr> <td> Интересно, кто я?<br/> </td></tr></table> 
  1769     </p></li>
  1770     <li><p>
  1771     Если комментарий содержит несколько строк,
  1772     его можно вставить в журнал следующим образом:
  1773 <pre class='cline'>
  1774 \$ whoami
  1775 </pre>
  1776 <pre class='output'>
  1777 user
  1778 </pre>
  1779 <pre class='cline'>
  1780 \$ cat > /dev/null #^ Интересно, кто я?
  1781 </pre>
  1782 <pre class='output'>
  1783 Программа whoami выводит имя пользователя, под которым 
  1784 мы зарегистрировались в системе.
  1785 -
  1786 Она не может ответить на вопрос о нашем назначении 
  1787 в этом мире.
  1788 </pre>
  1789     В журнале это будет выглядеть так:
  1790 <table>
  1791 <tr class='command'>
  1792 <td class='script'>
  1793 <pre class='cline'>
  1794 \$ whoami</pre>
  1795 <pre class='output'>user
  1796 </pre>
  1797 <table class='note'><tr><td class='note_title'>Интересно, кто я?</td></tr><tr><td width='100%' class='note_text'>
  1798 Программа whoami выводит имя пользователя, под которым<br/>
  1799 мы зарегистрировались в системе.<br/>
  1800 <br/>
  1801 Она не может ответить на вопрос о нашем назначении<br/>
  1802 в этом мире.<br/>
  1803 </td></tr></table>
  1804 </td>
  1805 </tr>
  1806 </table>
  1807     Для разделения нескольких абзацев между собой
  1808     используйте символ "-", один в строке.
  1809     <br/>
  1810 </p></li>
  1811     <li><p>
  1812     Комментарии, не относящиеся непосредственно ни к какой из команд, 
  1813     добавляются точно таким же способом, только вместо симолов #^ или #v 
  1814     нужно использовать символы #=
  1815     </p></li>
  1817     <p><li>
  1818     Содержимое файла может быть показано в журнале.
  1819     Для этого его нужно вывести с помощью программы cat.
  1820     Если вывод команды отметить симоволами #!, 
  1821     содержимое файла будет показано в журнале
  1822     в специально отведённой для этого секции.
  1823     </li></p>
  1825     <p>
  1826     <li>
  1827     Для того чтобы вставить скриншот интересующего вас окна в журнал,
  1828     нужно воспользоваться командой l3shot.
  1829     После того как команда вызвана, нужно с помощью мыши выбрать окно, которое
  1830     должно быть в журнале.
  1831     </li>
  1832     </p>
  1834     <p>
  1835     <li>
  1836     Команды в журнале расположены в хронологическом порядке.
  1837     Если две команды давались одна за другой, но на разных терминалах,
  1838     в журнале они будут рядом, даже если они не имеют друг к другу никакого отношения.
  1839 <pre>
  1840 1
  1841     2
  1842 3   
  1843     4
  1844 </pre>
  1845     Группы команд, выполненных на разных терминалах, разделяются специальной линией.
  1846     Под этой линией в правом углу показано имя терминала, на котором выполнялись команды.
  1847     Для того чтобы посмотреть команды только одного сенса, 
  1848     нужно щёкнуть по этому названию.
  1849     </li>
  1850     </p>
  1851 </ol>
  1852 HELP
  1854 $Html_About = <<ABOUT;
  1855     <p>
  1856     <a href='http://xgu.ru/lilalo/'>LiLaLo</a> (L3) расшифровывается как Live Lab Log.<br/>
  1857     Программа разработана для повышения эффективности обучения Unix/Linux-системам.<br/>
  1858     (c) Игорь Чубин, 2004-2008<br/>
  1859     </p>
  1860 ABOUT
  1861 $Html_About.='$Id$ </p>';
  1863 $Html_JavaScript = <<JS;
  1864     function getElementsByClassName(Class_Name)
  1865     {
  1866         var Result=new Array();
  1867         var All_Elements=document.all || document.getElementsByTagName('*');
  1868         for (i=0; i<All_Elements.length; i++)
  1869             if (All_Elements[i].className==Class_Name)
  1870         Result.push(All_Elements[i]);
  1871         return Result;
  1872     }
  1873     function ShowHide (name)
  1874     {
  1875         elements=getElementsByClassName(name);
  1876         for(i=0; i<elements.length; i++)
  1877             if (elements[i].style.display == "none")
  1878                 elements[i].style.display = "";
  1879             else
  1880                 elements[i].style.display = "none";
  1881             //if (elements[i].style.visibility == "hidden")
  1882             //  elements[i].style.visibility = "visible";
  1883             //else
  1884             //  elements[i].style.visibility = "hidden";
  1885     }
  1886     function filter_by_output(text)
  1887     {
  1889         var jjj=0;
  1891         elements=getElementsByClassName('command');
  1892         for(i=0; i<elements.length; i++) {
  1893             subelems = elements[i].getElementsByTagName('pre');
  1894             for(j=0; j<subelems.length; j++) {
  1895                 if (subelems[j].className = 'output') {
  1896                     var str = new String(subelems[j].nodeValue);
  1897                     if (jjj != 1) { 
  1898                         alert(str);
  1899                         jjj=1;
  1900                     }
  1901                     if (str.indexOf(text) >0) 
  1902                         subelems[j].style.display = "none";
  1903                     else
  1904                         subelems[j].style.display = "";
  1906                 }
  1908             }
  1909         }       
  1911     }
  1912 JS
  1914 $SetCursorPosition_JS = <<JS;
  1915 function setCursorPosition(oInput,oStart,oEnd) {
  1916     oInput.focus();
  1917     if( oInput.setSelectionRange ) {
  1918         oInput.setSelectionRange(oStart,oEnd);
  1919     } else if( oInput.createTextRange ) {
  1920         var range = oInput.createTextRange();
  1921         range.collapse(true);
  1922         range.moveEnd('character',oEnd);
  1923         range.moveStart('character',oStart);
  1924         range.select();
  1925     }
  1926 }
  1927 JS
  1929 %Search_Machines = (
  1930         "google" =>     {   "query" =>  "http://www.google.com/search?q=" ,
  1931                     "icon"  =>  "$Config{frontend_google_ico}" },
  1932         "freebsd" =>    {   "query" =>  "http://www.freebsd.org/cgi/man.cgi?query=",
  1933                     "icon"  =>  "$Config{frontend_freebsd_ico}" },
  1934         "linux"  =>     {   "query" =>  "http://man.he.net/?topic=",
  1935                     "icon"  =>  "$Config{frontend_linux_ico}"},
  1936         "opennet"  =>   {   "query" =>  "http://www.opennet.ru/search.shtml?words=",
  1937                     "icon"  =>  "$Config{frontend_opennet_ico}"},
  1938         "local" =>  {   "query" =>  "http://www.freebsd.org/cgi/man.cgi?query=",
  1939                     "icon"  =>  "$Config{frontend_local_ico}" },
  1941     );
  1943 %Elements_Visibility = (
  1944         "0 new_commands_table"      =>  "новые команды",
  1945         "1 diff"      =>  "редактор",
  1946         "2 time"      =>  "время",
  1947         "3 ttychange"     =>  "терминал",
  1948         "4 wrong_output wrong_cline wrong_root_output wrong_root_cline" 
  1949                 =>  "команды с ненулевым кодом завершения",
  1950         "5 mistyped_output mistyped_cline mistyped_root_output mistyped_root_cline" 
  1951                 =>  "неверно набранные команды",
  1952         "6 interrupted_output interrupted_cline interrupted_root_output interrupted_root_cline" 
  1953                 =>  "прерванные команды",
  1954         "7 tab_completion_output tab_completion_cline"    
  1955                 =>  "продолжение с помощью tab"
  1956 );
  1958 @Day_Name      = qw/ Воскресенье Понедельник Вторник Среда Четверг Пятница Суббота /;
  1959 @Month_Name    = qw/ Январь Февраль Март Апрель Май Июнь Июль Август Сентябрь Октябрь Ноябрь Декабрь /;
  1960 @Of_Month_Name = qw/ Января Февраля Марта Апреля Мая Июня Июля Августа Сентября Октября Ноября Декабря /;
  1961 }
  1966 # Временно удалённый код
  1967 # Возможно, он не понадобится уже никогда
  1970 sub search_by
  1971 {
  1972     my $sm = shift;
  1973     my $topic = shift;
  1974     $topic =~ s/ /+/;
  1976     return "<a href='". $Search_Machines{$sm}->{"query"}."$topic'><img width='16' height='16' src='".
  1977                 $Search_Machines{$sm}->{"icon"}."' border='0'/></a>";
  1978 }
  1983 ########################################################################################
  1984 #
  1985 # mywi
  1986 #
  1987 # 
  1988 #
  1989 #
  1990 #
  1991 #
  1992 #
  1996 sub mywi_init
  1997 {
  1998     our $MyWiFile = "/home/igor/mywi/mywi.txt";
  1999     our $MyWiLog = "/home/igor/mywi/mywi.log";
  2000     our $section="";
  2002     our @MywiTXT;       # Массив текстовых записей mywi
  2003     our %MywiHASH;      # Хэш массивов записей
  2004     our %Query;
  2006     load_mywitxt($MyWiFile, \@MywiTXT, \%MywiHASH);
  2007 }
  2009 sub mywi_process_query($)
  2010 #
  2011 # Сделать подсказку по заданному запросу
  2012 # $_[0] - тема для подсказки
  2013 # 
  2014 # Возвращает:
  2015 #   строку-подсказку
  2016 #
  2017 {
  2018     my $query = shift;
  2019     parse_query($query, \%Query);
  2020     $result = search_in_txt(\%Query, \@MywiTXT, \%MywiHASH);
  2022     if (!$result) {
  2023         #add_to_log(\%Query, $MyWiLog);
  2024         return "$query nothing appropriate.  Logged. ".join (";",%Query);
  2025     }   
  2027     return $result;
  2028 }
  2030 ####################################################################################
  2031 #                                   private section
  2032 ####################################################################################
  2034 sub load_mywitxt
  2035 #
  2036 # Загрузить файл с записями Mywi_TXT
  2037 # в массив
  2038 # $_[0] - указатель на массив для загрузки
  2039 # $_[1] - имя файла для загрузки
  2040 # 
  2041 {
  2042     my $MyWiFile = $_[0];
  2043     my $MywiTXT = $_[1];
  2044     my $MywiHASH = $_[2];
  2046     open (MW, "$MyWiFile") or die "Can't open $MyWiFile for reading";
  2047     binmode MW, ":utf8";
  2048     @{$MywiTXT} = <MW>;
  2049     close (MWF);
  2051     for my $mywi_line (@{$MywiTXT}) {
  2052         my $topic = $mywi_line;
  2053         $topic =~ s@\s*\(.*\n@@;
  2054         push @{$$MywiHASH{"$topic"}}, $mywi_line;
  2055 #        $MywiHASH{"$topic"} .= $mywi_line;
  2056     }
  2057 }
  2059 sub parse_query
  2060 #
  2061 # Строка запроса:
  2062 #   [format:]topic[(section)]
  2063 # Элементы format и topic являются не обязательными
  2064 #
  2065 # $_[0] - строка запроса
  2066 # $_[1] - ссылка на хэш запроса
  2067 #
  2068 {
  2069     my $query_string = shift;
  2070     my $query_hash = shift;
  2072     %{$query_hash} = (
  2073         "format"    =>  "txt",
  2074         "section"   =>  "",
  2075         "topic" =>  "",
  2076     );
  2078     if ($query_string =~ s/^([^:]*)://) {
  2079         $query_hash->{"format"} = $1 || "txt";
  2080     }
  2081     if ($query_string =~ s/\(([^(]*)\)$//) {
  2082         $query_hash->{"section"} = $1 || "";
  2083     }
  2084     $query_hash->{"topic"} = $query_string;
  2085 }
  2088 sub search_in_txt
  2089 #
  2090 # Выполнить поиск в текстовой базе 
  2091 # по известному запросу
  2092 # $_[0] -- ссылка на хэш запроса
  2093 # $_[1] -- ссылка на массив текстовых записей
  2094 # $_[2] -- ссылка на хэш массивов текстовых записей
  2095 # Результат:
  2096 #   найденная текстовая запись в заданном формате
  2097 #
  2098 {
  2099     my %Query = %{$_[0]};
  2100     my %MywiHASH = %{$_[2]};
  2102     my $topic = $Query{"topic"};
  2103     my $section = $Query{"section"};
  2104     my $result = "";
  2106     return join("\n",@{$MywiHASH{"$topic"}})."\n";
  2108     for my $l (@{$$_[2]{$topic}}) {
  2109 #    for my $l (@{$_[1]}) {
  2110         my $line = $l;
  2111         if (
  2112             ($section and $line =~ /^\s*\Q$topic\E\s*\($section*\)\s*-/ )
  2113             or (not $section and $line =~ /^\s*\Q$topic\E\s*(\([^)]*\)?)\s*-/) ) {
  2114             $line =~ s/^.* -//mg if ($Config{"short"});
  2115             $result .= "<para>$line</para>";
  2116         }
  2117     }
  2118     return $result;
  2119 }
  2122 sub add_to_log($$)
  2123 #
  2124 # Если в базе отсутствует информация по данной теме, 
  2125 # сделать предположение доступным способом
  2126 # и добавить его в базу
  2127 # или просто сделать отметку о необходимости 
  2128 # расширения базы
  2129 #
  2130 # Добавить запись в журнал
  2131 # $_[0] - запись (ссылка на хэш)
  2132 # $_[1] - имя файла-журнала
  2133 #
  2134 {
  2135     my $query = $_[0];
  2136     my $MyWiLog = $_[1];
  2138     open (MWF, ">>:utf8", $MyWiLog) or die "Can't open $MyWiLog for writing";
  2139     my $my_guess = mywi_guess($query);
  2140     print MWF "$my_guess\n";
  2141     close(MWF);
  2142 }
  2144 sub mywi_guess($)
  2145 # Сформировать исходную строку для журнала по заданному запросу
  2146 # Если секция принадлежит 0..9, в качестве основы для результирующего текста использовать whatis
  2147 # $_[0] - запись (ссылка на хэш)
  2148 # 
  2149 # Возвращает:
  2150 #   строку-предположение
  2151 {
  2152     my %query = %{$_[0]};
  2154     my $topic = $query{"topic"};
  2155     my $section = $query{"section"};
  2157     my $result = "$topic($section)";
  2158     if (!$section or $section =~ /^[1-9]$/)
  2159     {
  2160         # Запрос из категории 1-9
  2161         # Об этом может знать whatis
  2162         $result = `LANG=C whatis -- "$topic"`;
  2163         if ($result =~ /nothing appropriate/i) {
  2164             $result = $topic;
  2165             $result .= "($section)" if $section;
  2166         }
  2167         else {
  2168             1 while ($result =~ s/(\s+)-(\s+)/$1+$2/sg);
  2169             $result =~ s/\s+\(/(/;
  2170             chomp $result;
  2171         }
  2172     }   
  2173     return $result;
  2174 }
