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