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