lilalo
view l3-frontend @ 91:d3182b751893
Раскомментировал вставку хинтов
| author | devi | 
|---|---|
| date | Mon Mar 06 10:22:13 2006 +0200 (2006-03-06) | 
| parents | 62001c1e3295 | 
| children | 45196265d30e | 
 line source
     1 #!/usr/bin/perl -w
     3 use IO::Socket;
     4 use lib '.';
     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 $Mywi_Socket;
    13 our %Sessions;
    15 our %filter;
    16 our $filter_url;
    17 sub init_filter;
    19 our %Files;
    21 # vvv Инициализация переменных выполняется процедурой init_variables
    22 our @Day_Name;
    23 our @Month_Name;
    24 our @Of_Month_Name;
    25 our %Search_Machines;
    26 our %Elements_Visibility;
    27 # ^^^
    29 our %Stat;
    30 our %frequency_of_command; # Сколько раз в журнале встречается какая команда
    31 our $table_number=1;
    33 my %mywi_cache_for;         # Кэш для экономии обращений к mywi
    35 sub make_comment;
    36 sub make_new_entries_table;
    37 sub load_command_lines_from_xml;
    38 sub load_sessions_from_xml;
    39 sub sort_command_lines;
    40 sub process_command_lines;
    41 sub init_variables;
    42 sub main;
    43 sub collapse_list($);
    45 sub minutes_passed;
    47 sub print_all_txt;
    48 sub print_all_html;
    49 sub print_edit_all_html;
    50 sub print_command_lines_html;
    51 sub print_command_lines_txt;
    52 sub print_files_html;
    53 sub print_stat_html;
    54 sub print_header_html;
    55 sub print_footer_html;
    57 main();
    59 sub main
    60 {
    61     $| = 1;
    63     init_variables();
    64     init_config();
    65     $Config{frontend_ico_path}=$Config{frontend_css};
    66     $Config{frontend_ico_path}=~s@/[^/]*$@@;
    67     init_filter();
    69     open_mywi_socket();
    70     load_command_lines_from_xml($Config{"backend_datafile"});
    71     load_sessions_from_xml($Config{"backend_datafile"});
    72     sort_command_lines;
    73     process_command_lines;
    74     if (defined($filter{action}) && $filter{action} eq "edit") {
    75         print_edit_all_html($Config{"output"});
    76     }
    77     else {
    78         print_all_html($Config{"output"});
    79     }
    80     close_mywi_socket;
    81 }
    83 sub init_filter
    84 {
    85     if ($Config{filter}) {
    86         # Инициализация фильтра
    87         for (split /&/,$Config{filter}) {
    88             my ($var, $val) = split /=/;
    89             $filter{$var} = $val || "";
    90         }
    91     }
    92     $filter_url = join ("&", map("$_=$filter{$_}", keys %filter));
    93 }
    95 # extract_from_cline
    97 # In:   $what       = commands | args
    98 # Out:  return      ссылка на хэш, содержащий результаты разбора
    99 #                   команда => позиция
   101 # Разобрать командную строку $_[1] и возвратить хэш, содержащий 
   102 # номер первого появление команды в строке:
   103 #   команда => первая позиция
   104 sub extract_from_cline
   105 {
   106     my $what = $_[0];
   107     my $cline = $_[1];
   108     my @lists = split /\;/, $cline;
   111     my @command_lines = ();
   112     for my $command_list (@lists) {
   113         push(@command_lines, split(/\|/, $command_list));
   114     }
   116     my %position_of_command;
   117     my %position_of_arg;
   118     my $i=0;
   119     for my $command_line (@command_lines) {
   120         $command_line =~ s@^\s*@@;
   121         $command_line =~ /\s*(\S+)\s*(.*)/;
   122         if ($1 && $1 eq "sudo" ) {
   123             $position_of_command{"$1"}=$i++;
   124             $command_line =~ s/\s*sudo\s+//;
   125         }
   126         if ($command_line !~ m@^\s*\S*/etc/@) {
   127             $command_line =~ s@^\s*\S+/@@;
   128         }
   130         $command_line =~ /\s*(\S+)\s*(.*)/;
   131         my $command = $1;
   132         my $args = $2;
   133         if ($command && !defined $position_of_command{"$command"}) {
   134                 $position_of_command{"$command"}=$i++;
   135         };  
   136         if ($args) {
   137             my @args = split (/\s+/, $args);
   138             for my $a (@args) {
   139                 $position_of_arg{"$a"}=$i++
   140                     if !defined $position_of_arg{"$a"};
   141             };  
   142         }
   143     }
   145     if ($what eq "commands") {
   146         return \%position_of_command;
   147     } else {
   148         return \%position_of_arg;
   149     }
   151 }
   156 #
   157 # Подпрограммы для работы с mywi
   158 #
   160 sub open_mywi_socket
   161 {
   162     $Mywi_Socket = IO::Socket::INET->new(
   163                 PeerAddr => $Config{mywi_server},
   164                 PeerPort => $Config{mywi_port},
   165                 Proto    => "tcp",
   166                 Type     => SOCK_STREAM);
   167 }
   169 sub close_mywi_socket
   170 {
   171     close ($Mywi_Socket) if $Mywi_Socket ;
   172 }
   175 sub mywi_client
   176 {
   177     my $query = $_[0];
   178     my $mywi;
   180     open_mywi_socket;
   181     if ($Mywi_Socket) {
   182         local $| = 1;
   183         local $/ = "";
   184         print $Mywi_Socket $query."\n";
   185         $mywi = <$Mywi_Socket>;
   186         $mywi = "" if $mywi =~ /nothing app/;
   187     }
   188     close_mywi_socket;
   189     return $mywi;
   190 }
   192 sub make_comment
   193 {
   194     my $cline = $_[0];
   195     #my $files = $_[1];
   197     my @comments;
   198     my @commands = keys %{extract_from_cline("commands", $cline)};
   199     my @args = keys %{extract_from_cline("args", $cline)};
   200     return if (!@commands && !@args);
   201     #return "commands=".join(" ",@commands)."; files=".join(" ",@files);
   203     # Commands
   204     for my $command (@commands) {
   205         $command =~ s/'//g;
   206         $frequency_of_command{$command}++;
   207         if (!$Commands_Description{$command}) {
   208             $mywi_cache_for{$command} ||= mywi_client ($command) || "";
   209             my $mywi = join ("\n", grep(/\([18]|sh|script\)/, split(/\n/, $mywi_cache_for{$command})));
   210             $mywi =~ s/\s+/ /;
   211             if ($mywi !~ /^\s*$/) {
   212                 $Commands_Description{$command} = $mywi;
   213             }
   214             else {
   215                 next;
   216             }
   217         }
   219         push @comments, $Commands_Description{$command};
   220     }
   221     return join("
\n", @comments);
   223     # Files
   224     for my $arg (@args) {
   225         $arg =~ s/'//g;
   226         if (!$Args_Description{$arg}) {
   227             my $mywi;
   228             $mywi = mywi_client ($arg);
   229             $mywi = join ("\n", grep(/\([5]\)/, split(/\n/, $mywi)));
   230             $mywi =~ s/\s+/ /;
   231             if ($mywi !~ /^\s*$/) {
   232                 $Args_Description{$arg} = $mywi;
   233             }
   234             else {
   235                 next;
   236             }
   237         }
   239         push @comments, $Args_Description{$arg};
   240     }
   242 }
   244 =cut
   245 Процедура load_command_lines_from_xml выполняет загрузку разобранного lab-скрипта
   246 из XML-документа в переменную @Command_Lines
   248 # In:       $datafile           имя файла
   249 # Out:      @CommandLines       загруженные командные строки
   251 Предупреждение!
   252 Процедура не в состоянии обрабатывать XML-документ любой структуры.
   253 В действительности файл cache из которого загружаются данные 
   254 просто напоминает XML с виду.
   255 =cut
   256 sub load_command_lines_from_xml
   257 {
   258     my $datafile = $_[0];
   260     open (CLASS, $datafile)
   261         or die "Can't open file with xml lablog ",$datafile,"\n";
   262     local $/;
   263     binmode CLASS, ":utf8";
   264     $data = <CLASS>;
   265     close(CLASS);
   267     for $command ($data =~ m@<command>(.*?)</command>@sg) {
   268         my %cl;
   269         while ($command =~ m@<([^>]*?)>(.*?)</\1>@sg) {
   270             $cl{$1} = $2;
   271         }
   272         push @Command_Lines, \%cl;
   273     }
   274 }
   276 sub load_sessions_from_xml
   277 {
   278     my $datafile = $_[0];
   280     open (CLASS,  $datafile)
   281         or die "Can't open file with xml lablog ",$datafile,"\n";
   282     local $/;
   283     binmode CLASS, ":utf8";
   284     my $data = <CLASS>;
   285     close(CLASS);
   287     my $i=0;
   288     for my $session ($data =~ m@<session>(.*?)</session>@msg) {
   289         my %session_hash;
   290         while ($session =~ m@<([^>]*?)>(.*?)</\1>@sg) {
   291             $session_hash{$1} = $2;
   292         }
   293         $Sessions{$session_hash{local_session_id}} = \%session_hash;
   294     }
   295 }
   298 # sort_command_lines
   299 # In:   @Command_Lines
   300 # Out:  @Command_Lies_Index
   302 sub sort_command_lines
   303 {
   305     my @index;
   306     for (my $i=0;$i<=$#Command_Lines;$i++) {
   307         $index[$i]=$i;
   308     }
   310     @Command_Lines_Index = sort {
   311         $Command_Lines[$index[$a]]->{"time"} <=> $Command_Lines[$index[$b]]->{"time"}
   312     } @index;
   314 }
   316 ##################
   317 # process_command_lines
   318 #
   319 # Обрабатываются командные строки @Command_Lines
   320 # Для каждой строки определяется:
   321 #   class   класс    
   322 #   note    комментарий 
   323 #
   324 # In:        @Command_Lines_Index
   325 # In-Out:    @Command_Lines
   327 sub process_command_lines
   328 {
   330 COMMAND_LINE_PROCESSING:
   331     for my $i (@Command_Lines_Index) {
   332         my $cl = \$Command_Lines[$i];
   334         next if !$cl;
   336         for my $filter_key (keys %filter) {
   337             next COMMAND_LINE_PROCESSING
   338                 if defined($$cl->{local_session_id})
   339                 && defined($Sessions{$$cl->{local_session_id}}->{$filter_key})
   340                 && $Sessions{$$cl->{local_session_id}}->{$filter_key} ne $filter{$filter_key};
   341         }
   343         $$cl->{id} = $$cl->{"time"};
   345         $$cl->{err} ||=0;
   347         # Класс команды
   349         $$cl->{"class"} =   $$cl->{"err"} eq 130 ?  "interrupted"
   350                         :   $$cl->{"err"} eq 127 ?  "mistyped"
   351                         :   $$cl->{"err"}        ?  "wrong"
   352                         :                           "normal";
   354         if ($$cl->{"cline"} && 
   355             $$cl->{"cline"} =~ /[^|`]\s*sudo/
   356             || $$cl->{"uid"} eq 0) {
   357             $$cl->{"class"}.="_root";
   358         }
   360         my $hint;
   361         $hint = make_comment($$cl->{"cline"});
   362         if ($hint) {
   363             $$cl->{hint} = $hint;
   364         }
   365 #        $$cl->{hint}="";
   367 # Выводим <head_lines> верхних строк
   368 # и <tail_lines> нижних строк,
   369 # если эти параметры существуют
   370         my $output="";
   372         if ($$cl->{"last_command"} eq "cat" && !$$cl->{"err"} && !($$cl->{"cline"} =~ /</)) {
   373             my $filename = $$cl->{"cline"};
   374             $filename =~ s/.*\s+(\S+)\s*$/$1/;
   375             $Files{$filename}->{"content"} = $$cl->{"output"};
   376            $Files{$filename}->{"source_command_id"} = $$cl->{"id"}
   377         }
   378         my @lines = split '\n', $$cl->{"output"};
   379         if ((
   380              $Config{"head_lines"} 
   381              || $Config{"tail_lines"}
   382              )
   383              && $#lines >  $Config{"head_lines"} + $Config{"tail_lines"} ) {
   384 #
   385             for (my $i=0; $i<= $#lines && $i < $Config{"head_lines"}; $i++) {
   386                 $output .= $lines[$i]."\n";
   387             }
   388             $output .= $Config{"skip_text"}."\n";
   390             my $start_line=$#lines-$Config{"tail_lines"}+1;
   391             for (my $i=$start_line; $i<= $#lines; $i++) {
   392                 $output .= $lines[$i]."\n";
   393             }
   394         } 
   395         else {
   396            $output = $$cl->{"output"};
   397         }
   398         $$cl->{short_output} = $output;
   400 #Обработка пометок
   401 #  Если несколько пометок (notes) идут подряд, 
   402 #  они все объединяются
   404         if ($$cl->{cline} =~ /l3shot/) {
   405                 if ($$cl->{output} =~ m@Screenshot is written to.*/(.*)\.xwd@) {
   406                     $$cl->{screenshot}="$1";
   407                 }
   408         }
   410         if ($$cl->{cline}=~ m@cat[^#]*#([\^=v])\s*(.*)@) {
   412             my $note_operator = $1;
   413             my $note_title = $2;
   415             if ($note_operator eq "=") {
   416                 $$cl->{"class"} = "note";
   417                 $$cl->{"note"} = $$cl->{"output"};
   418                 $$cl->{"note_title"} = $2;
   419             }
   420             else {
   421                 my $j = $i;
   422                 if ($note_operator eq "^") {
   423                     $j--;
   424                     $j-- while ($j >=0  && (!$Command_Lines[$j] || $Command_Lines[$j]->{tty} ne $$cl->{tty}));
   425                 }
   426                 elsif ($note_operator eq "v") {
   427                     $j++;
   428                     $j++ while ($j <= @Command_Lines  && (!$Command_Lines[$j] || $Command_Lines[$j]->{tty} ne $$cl->{tty}));
   429                 }
   430                 $Command_Lines[$j]->{note_title}=$note_title;
   431                 $Command_Lines[$j]->{note}.=$$cl->{output};
   432                 $$cl=0;
   433             }
   434         }
   435         elsif ($$cl->{cline}=~ /#([\^=v])(.*)/) {
   437             my $note_operator = $1;
   438             my $note_text = $2;
   440             if ($note_operator eq "=") {
   441                 $$cl->{"class"} = "note";
   442                 $$cl->{"note"} = $note_text;
   443             }
   444             else {
   445                 my $j=$i;
   446                 if ($note_operator eq "^") {
   447                     $j--;
   448                     $j-- while ($j >=0  && (!$Command_Lines[$j] || $Command_Lines[$j]->{tty} ne $$cl->{tty}));
   449                 }
   450                 elsif ($note_operator eq "v") {
   451                     $j++;
   452                     $j++ while ($j <= @Command_Lines  && $Command_Lines[$j]->{tty} ne $$cl->{tty} || !$Command_Lines[$j]);
   453                 }
   454                 $Command_Lines[$j]->{note}.="$note_text\n";
   455                 $$cl=0;
   456             }
   457         }
   458         if ($$cl->{"class"} eq "note") {
   459                 my $note_html = $$cl->{note};
   460                 $note_html = join ("\n", map ("<p>$_</p>", split (/-\n/, $note_html)));
   461                 $note_html =~ s@(http:[a-zA-Z.0-9/?\_%-]*)@<a href='$1'>$1</a>@g;
   462                 $note_html =~ s@(www\.[a-zA-Z.0-9/?\_%-]*)@<a href='$1'>$1</a>@g;
   463                 $$cl->{"note_html"} = $note_html;
   464         }
   465     }   
   467 }
   470 =cut
   471 Процедура print_command_lines выводит HTML-представление
   472 разобранного lab-скрипта. 
   474 Разобранный lab-скрипт должен находиться в массиве @Command_Lines
   475 =cut
   477 sub print_command_lines_html
   478 {
   480     my @toc;                # Оглавление
   481     my $note_number=0;
   483     my $result = q();
   484     my $this_day_resut = q();
   486     my $cl;
   487     my $last_tty="";
   488     my $last_session="";
   489     my $last_day=q();
   490     my $last_wday=q();
   491     my $in_range=0;
   493     my $current_command=0;
   495     my @known_commands;
   499     $Stat{LastCommand}   ||= 0;
   500     $Stat{TotalCommands} ||= 0;
   501     $Stat{ErrorCommands} ||= 0;
   502     $Stat{MistypedCommands} ||= 0;
   504     my %new_entries_of = (
   505         "1 1"     =>   "программы пользователя",
   506         "2 8"     =>   "программы администратора",
   507         "3 sh"    =>   "команды интерпретатора",
   508         "4 script"=>   "скрипты",
   509     );
   511 COMMAND_LINE:
   512     for my $k (@Command_Lines_Index) {
   514         my $cl=$Command_Lines[$Command_Lines_Index[$current_command++]];
   515         next unless $cl;
   517 # Пропускаем команды, с одинаковым временем
   518 # Это не совсем правильно.
   519 # Возможно, что это команды, набираемые с помощью <completion>
   520 # или запомненные с помощью <ctrl-c>
   522         next if $Stat{LastCommand} == $cl->{time};
   524 # Пропускаем строки, которые противоречат фильтру
   525 # Если у нас недостаточно информации о том, подходит строка под  фильтр или нет, 
   526 # мы её выводим
   528         for my $filter_key (keys %filter) {
   529             next COMMAND_LINE 
   530                 if defined($cl->{local_session_id})
   531                 && defined($Sessions{$cl->{local_session_id}}->{$filter_key})
   532                 && $Sessions{$cl->{local_session_id}}->{$filter_key} ne $filter{$filter_key};
   533         }
   535 # Набираем статистику
   536 # Хэш %Stat
   538         $Stat{FirstCommand} = $cl->{time} unless $Stat{FirstCommand};
   539         if ($cl->{time} - $Stat{LastCommand} < $Config{stat_inactivity_interval}) {
   540             $Stat{TotalTime} += $cl->{time} - $Stat{LastCommand}
   541         }
   542         my $seconds_since_last_command = $cl->{time} - $Stat{LastCommand};
   544         if ($Stat{LastCommand} > $cl->{time}) {
   545                $result .= "Время идёт вспять<br/>";
   546         };
   547         $Stat{LastCommand} = $cl->{time};
   548         $Stat{TotalCommands}++;
   550 # Пропускаем строки, выходящие за границу "signature",
   551 # при условии, что границы указаны
   552 # Пропускаем неправильные/прерванные/другие команды
   553         if ($Config{"from"} && $cl->{"cline"} =~ /$Config{"signature"}\s*$Config{"from"}/) {
   554             $in_range=1;
   555             next;
   556         }
   557         if ($Config{"to"} && $cl->{"cline"} =~ /$Config{"signature"}\s*$Config{"to"}/) {
   558             $in_range=0;
   559             next;
   560         }
   561         next    if ($Config{"from"} && $Config{"to"}   && !$in_range) 
   562                 || ($Config{"skip_empty"} =~ /^y/i     && $cl->{"cline"} =~ /^\s*$/ )
   563                 || ($Config{"skip_wrong"} =~ /^y/i     && $cl->{"err"} != 0)
   564                 || ($Config{"skip_interrupted"} =~ /^y/i && $cl->{"err"} == 130);
   569 #
   570 ##
   571 ## Начинается собственно вывод
   572 ##
   573 #
   575 ### Сначала обрабатываем границы разделов
   576 ### Если тип команды "note", это граница
   578         if ($cl->{class} eq "note") {
   579             $this_day_result .= "<tr><td colspan='6'>"
   580                              .  "<h4 id='note$note_number'>".$cl->{note_title}."</h4>" if $cl->{note_title}
   581                              .  "".$cl->{note_html}."<p/><p/></td></tr>";
   583             if ($cl->{note_title}) {
   584                 push @{$toc[@toc]},"<a href='#note$note_number'>".$cl->{note_title}."</a>";
   585                 $note_number++;
   586             }
   587             next;
   588         }
   590         my ($sec,$min,$hour,$day,$mon,$year,$wday,$yday,$isdst) = localtime($cl->{time});
   592         # Добавляем спереди 0 для удобочитаемости
   593         $min  = "0".$min  if $min  =~ /^.$/;
   594         $hour = "0".$hour if $hour =~ /^.$/;
   595         $sec  = "0".$sec  if $sec  =~ /^.$/;
   597         $class=$cl->{"class"};
   598         $Stat{ErrorCommands}++          if $class =~ /wrong/;
   599         $Stat{MistypedCommands}++       if $class =~ /mistype/;
   601 # DAY CHANGE
   602         if ( $last_day ne $day) {
   603             if ($last_day) {
   605 # Вычисляем разность множеств.
   606 # Что-то вроде этого, если бы так можно было писать:
   607 #   @new_commands = keys %frequency_of_command - @known_commands;
   610                 $result .= "<h3 id='day$last_day'>".$Day_Name[$last_wday]."</h3>";
   611                 for my $entry_class (sort keys %new_entries_of) {
   612                     my $table_caption = "Таблица ".$table_number++.".".$Day_Name[$last_wday]
   613                                         .". Новые ".$new_entries_of{$entry_class};
   614                     my $new_commands_section = make_new_entries_table(
   615                                                 $table_caption, 
   616                                                 $entry_class=~/[0-9]+\s+(.*)/, 
   617                                                 \@known_commands);
   618                 }
   619                 @known_commands = keys %frequency_of_command;
   620                 $result .= $this_day_result;
   621             }
   623             push @toc, "<a href='#day$day'>".$Day_Name[$wday]."</a>\n";
   624             $last_day=$day;
   625             $last_wday=$wday;
   626             $this_day_result = q();
   627         }
   628         else {
   629             $this_day_result .= minutes_passed($seconds_since_last_command);
   630         }
   632         $this_day_result .= "<div class='command' id='command:".$cl->{"id"}."' >\n";
   634 # CONSOLE CHANGE
   635         if ($cl->{"tty"} && $last_tty ne $cl->{"tty"} && 0) {
   636             my $tty = $cl->{"tty"};
   637             $this_day_result .= "<div class='ttychange'>"
   638                                 . $tty
   639                                 ."</div>";
   640             $last_tty=$cl->{"tty"};
   641         }
   643 # Session change
   644         if ( $last_session ne $cl->{"local_session_id"}) {
   645             my $tty;
   646             if (defined $Sessions{$cl->{"local_session_id"}}->{"tty"}) {
   647                 $this_day_result .= "<div class='ttychange'><a href='?local_session_id=".$cl->{"local_session_id"}."'>"
   648                                 . $Sessions{$cl->{"local_session_id"}}->{"tty"}
   649                                 ."</a></div>";
   650             }
   651             $last_session=$cl->{"local_session_id"};
   652         }
   654 # TIME
   655         if ($Config{"show_time"} =~ /^y/i) {
   656             $this_day_result .= "<div class='time'>$hour:$min:$sec</div>" 
   657         }
   659 # COMMAND
   660         my $cline;
   661         $prompt_hint = join ("
", map("$_=$cl->{$_}", grep (!/^(output|diff)$/, sort(keys(%{$cl})))));
   662         $cline = "<span title='$prompt_hint'>".$cl->{"prompt"}."</span>".$cl->{"cline"};
   663         $cline =~ s/\n//;
   665         if ($cl->{"hint"}) {
   666             $cline = "<span title='$cl->{hint}' class='with_hint'>$cline</span>" ;
   667         } 
   668         else {
   669             $cline = "<span class='without_hint'>$cline</span>";
   670         }
   672         $this_day_result .= "<table cellpadding='0' cellspacing='0'><tr><td>\n<div class='cblock_$cl->{class}'>\n";
   673         $this_day_result .= "<div class='cline'>\n" . $cline ;      #cline
   674         $this_day_result .= "<span title='Код завершения ".$cl->{"err"}."'>\n"
   675                          .  "<img src='".$Config{frontend_ico_path}."/error.png'/>\n"
   676                          .  "</span>\n" if $cl->{"err"};
   677         $this_day_result .= "</div>\n";                             #cline
   679 # OUTPUT
   680         my $last_command = $cl->{"last_command"};
   681         if (!( 
   682         $Config{"suppress_editors"} =~ /^y/i && grep ($_ eq $last_command, @{$Config{"editors"}}) ||
   683         $Config{"suppress_pagers"}  =~ /^y/i && grep ($_ eq $last_command, @{$Config{"pagers"}}) ||
   684         $Config{"suppress_terminal"}=~ /^y/i && grep ($_ eq $last_command, @{$Config{"terminal"}})
   685             )) {
   686             $this_day_result .= "<pre class='output'>\n" . $cl->{short_output} . "</pre>\n";
   687         }
   689 # DIFF
   690         $this_day_result .= "<pre class='diff'>".$cl->{"diff"}."</pre>"
   691             if ( $Config{"show_diffs"} =~ /^y/i && $cl->{"diff"});
   692 # SHOT
   693         $this_day_result .= "<img src='"
   694                 .$Config{l3shot_path}
   695                 .$cl->{"screenshot"}
   696                 .$Config{l3shot_suffix}
   697                 ."' alt ='screenshot id ".$cl->{"screenshot"}
   698                 ."'/>"
   699             if ( $Config{"show_screenshots"} =~ /^y/i && $cl->{"screenshot"});
   701 #NOTES
   702         if ( $Config{"show_notes"} =~ /^y/i && $cl->{"note"}) {
   703             my $note=$cl->{"note"};
   704             $note =~ s/\n/<br\/>\n/msg;
   705             if (not $note =~ s@(http:[a-zA-Z.0-9/_?%-]*)@<a href='$1'>$1</a>@g) {
   706               $note =~ s@(www\.[a-zA-Z.0-9/_?%-]*)@<a href='$1'>$1</a>@g;
   707             };
   708             $this_day_result .= "<div class='note'>";
   709             $this_day_result .= "<div class='note_title'>".$cl->{note_title}."</div>" if $cl->{note_title};
   710             $this_day_result .= "<div class='note_text'>".$note."</div>";
   711             $this_day_result .= "</div>\n";
   712         }
   714         # Вывод очередной команды окончен
   715         $this_day_result .= "</div>\n";                     # cblock
   716         $this_day_result .= "</td></tr></table>\n"
   717                          .  "</div>\n";                     # command
   718     }
   719     last: {
   720         $result .= "<h3 id='day$last_day'>".$Day_Name[$last_wday]."</h3>";
   722         for my $entry_class (keys %new_entries_of) {
   723             my $table_caption = "Таблица ".$table_number++.".".$Day_Name[$last_wday]
   724                               . ". Новые ".$new_entries_of{$entry_class};
   725             my $new_commands_section = make_new_entries_table(
   726                                         $table_caption, 
   727                                         $entry_class=~/[0-9]+\s+(.*)/, 
   728                                         \@known_commands);
   729         }
   730         @known_commands = keys %frequency_of_command;
   731         $result .= $this_day_result;
   732    }
   734     return ($result, collapse_list (\@toc));
   736 }
   738 #############
   739 # make_new_entries_table
   740 #
   741 # Напечатать таблицу неизвестных команд
   742 #
   743 # In:       $_[0]       table_caption
   744 #           $_[1]       entries_class
   745 #           @_[2..]     known_commands
   746 # Out:
   748 sub make_new_entries_table
   749 {
   750     my $table_caption;
   751     my $entries_class = shift;
   752     my @known_commands = @{$_[0]};
   753     my $result = "";
   755     my %count;
   756     my @new_commands = ();
   757     for my $c (keys %frequency_of_command, @known_commands) {
   758         $count{$c}++
   759     }
   760     for my $c (keys %frequency_of_command) {
   761         push @new_commands, $c if $count{$c} != 2;
   762     }
   764     my $new_commands_section;
   765     if (@new_commands){
   766         my $hint;
   767         for my $c (reverse sort { $frequency_of_command{$a} <=> $frequency_of_command{$b} } @new_commands) {
   768                 $hint = make_comment($c);
   769                 next unless $hint;
   770                 my ($command, $hint) = $hint =~ m/(.*?) \s*- \s*(.*)/;
   771                 next unless $command =~ s/\($entries_class\)//i;
   772                 $new_commands_section .= "<tr><td valign='top'>$command</td><td>$hint</td></tr>";
   773         }
   774     }
   775     if ($new_commands_section) {
   776         $result .= "<table class='new_commands_table' width='700' cellspacing='0' cellpadding='0'>"
   777                 .  "<tr class='new_commands_caption'>"
   778                 .  "<td colspan='2' align='right'>$table_caption</td>"
   779                 .  "</tr>"
   780                 .  "<tr class='new_commands_header'>"
   781                 .  "<td width=100>Команда</td><td width=600>Описание</td>"
   782                 .  "</tr>"
   783                 .  $new_commands_section 
   784                 .  "</table>"
   785     }
   786     return $result;
   787 }
   789 #############
   790 # minutes_passed
   791 #
   792 #
   793 #
   794 # In:       $_[0]       seconds_since_last_command
   795 # Out:                  "minutes passed" text
   797 sub minutes_passed
   798 {
   799         my $seconds_since_last_command = shift;
   800         my $result = "";
   801         if ($seconds_since_last_command > 7200) {
   802             my $hours_passed =  int($seconds_since_last_command/3600);
   803             my $passed_word  = $hours_passed % 10 == 1 ? "прошла"
   804                                                          : "прошло";
   805             my $hours_word   = $hours_passed % 10 == 1 ?   "часа":
   806                                                            "часов";
   807             $result .= "<div class='much_time_passed'>"
   808                     .  $passed_word." >".$hours_passed." ".$hours_word
   809                     .  "</div>\n";
   810         }
   811         elsif ($seconds_since_last_command > 600) {
   812             my $minutes_passed =  int($seconds_since_last_command/60);
   815             my $passed_word  = $minutes_passed % 100 > 10 
   816                             && $minutes_passed % 100 < 20 ? "прошло"
   817                              : $minutes_passed % 10 == 1  ? "прошла"
   818                                                           : "прошло";
   820             my $minutes_word = $minutes_passed % 100 > 10 
   821                             && $minutes_passed % 100 < 20 ? "минут" :
   822                                $minutes_passed % 10 == 1 ? "минута":
   823                                $minutes_passed % 10 == 0 ? "минут" :
   824                                $minutes_passed % 10  > 4 ? "минут" :
   825                                                            "минуты";
   827             if ($seconds_since_last_command < 1800) {
   828                 $result .= "<div class='time_passed'>"
   829                         .  $passed_word." ".$minutes_passed." ".$minutes_word
   830                         .  "</div>\n";
   831             }
   832             else {
   833                 $result .= "<div class='much_time_passed'>"
   834                         .  $passed_word." ".$minutes_passed." ".$minutes_word
   835                         .  "</div>\n";
   836             }
   837         }
   838         return $result;
   839 }
   841 #############
   842 # print_all_txt
   843 #
   844 # Вывести журнал в текстовом формате
   845 #
   846 # In:       $_[0]       output_filename
   847 # Out:
   849 sub print_command_lines_txt
   850 {
   852     my $output_filename=$_[0];
   853     my $note_number=0;
   855     my $result = q();
   856     my $this_day_resut = q();
   858     my $cl;
   859     my $last_tty="";
   860     my $last_session="";
   861     my $last_day=q();
   862     my $last_wday=q();
   863     my $in_range=0;
   865     my $current_command=0;
   867     my $cursor_position = 0;
   870     if ($Config{filter}) {
   871         # Инициализация фильтра
   872         for (split /&/,$Config{filter}) {
   873             my ($var, $val) = split /=/;
   874             $filter{$var} = $val || "";
   875         }
   876     }
   879 COMMAND_LINE:
   880     for my $k (@Command_Lines_Index) {
   882         my $cl=$Command_Lines[$Command_Lines_Index[$current_command++]];
   883         next unless $cl;
   886 # Пропускаем строки, которые противоречат фильтру
   887 # Если у нас недостаточно информации о том, подходит строка под  фильтр или нет, 
   888 # мы её выводим
   890         for my $filter_key (keys %filter) {
   891             next COMMAND_LINE 
   892                 if defined($cl->{local_session_id})
   893                 && defined($Sessions{$cl->{local_session_id}}->{$filter_key})
   894                 && $Sessions{$cl->{local_session_id}}->{$filter_key} ne $filter{$filter_key};
   895         }
   897 # Пропускаем строки, выходящие за границу "signature",
   898 # при условии, что границы указаны
   899 # Пропускаем неправильные/прерванные/другие команды
   900         if ($Config{"from"} && $cl->{"cline"} =~ /$Config{"signature"}\s*$Config{"from"}/) {
   901             $in_range=1;
   902             next;
   903         }
   904         if ($Config{"to"} && $cl->{"cline"} =~ /$Config{"signature"}\s*$Config{"to"}/) {
   905             $in_range=0;
   906             next;
   907         }
   908         next    if ($Config{"from"} && $Config{"to"}   && !$in_range) 
   909                 || ($Config{"skip_empty"} =~ /^y/i     && $cl->{"cline"} =~ /^\s*$/ )
   910                 || ($Config{"skip_wrong"} =~ /^y/i     && $cl->{"err"} != 0)
   911                 || ($Config{"skip_interrupted"} =~ /^y/i && $cl->{"err"} == 130);
   914 #
   915 ##
   916 ## Начинается собственно вывод
   917 ##
   918 #
   920 ### Сначала обрабатываем границы разделов
   921 ### Если тип команды "note", это граница
   923         if ($cl->{class} eq "note") {
   924             $this_day_result .= " === ".$cl->{note_title}." === \n" if $cl->{note_title};
   925             $this_day_result .= $cl->{note}."\n";
   926             next;
   927         }
   929         my ($sec,$min,$hour,$day,$mon,$year,$wday,$yday,$isdst) = localtime($cl->{time});
   931         # Добавляем спереди 0 для удобочитаемости
   932         $min  = "0".$min  if $min  =~ /^.$/;
   933         $hour = "0".$hour if $hour =~ /^.$/;
   934         $sec  = "0".$sec  if $sec  =~ /^.$/;
   936         $class=$cl->{"class"};
   938 # DAY CHANGE
   939         if ( $last_day ne $day) {
   940             if ($last_day) {
   941                 $result .= "== ".$Day_Name[$last_wday]." == \n";
   942                 $result .= $this_day_result;
   943             }
   944             $last_day   = $day;
   945             $last_wday  = $wday;
   946             $this_day_result = q();
   947         }
   949 # CONSOLE CHANGE
   950         if ($cl->{"tty"} && $last_tty ne $cl->{"tty"} && 0) {
   951             my $tty = $cl->{"tty"};
   952             $this_day_result .= "         #l3: ------- другая консоль ----\n";
   953             $last_tty=$cl->{"tty"};
   954         }
   956 # Session change
   957         if ( $last_session ne $cl->{"local_session_id"}) {
   958             $this_day_result .= "# ------------------------------------------------------------"
   959                              .  "  l3: local_session_id=".$cl->{"local_session_id"}
   960                              .  " ---------------------------------- \n";
   961             $last_session=$cl->{"local_session_id"};
   962         }
   964 # TIME
   965         my @nl_counter = split (/\n/, $result);
   966         $cursor_position=length($result) - @nl_counter;
   968         if ($Config{"show_time"} =~ /^y/i) {
   969             $this_day_result .= "$hour:$min:$sec" 
   970         }
   972 # COMMAND
   973         $this_day_result .= " ".$cl->{"prompt"}.$cl->{"cline"}."\n";
   974         if ($cl->{"err"}) {
   975             $this_day_result .= "         #l3: err=".$cl->{'err'}."\n";
   976         }
   978 # OUTPUT
   979         my $last_command = $cl->{"last_command"};
   980         if (!( 
   981         $Config{"suppress_editors"} =~ /^y/i && grep ($_ eq $last_command, @{$Config{"editors"}}) ||
   982         $Config{"suppress_pagers"}  =~ /^y/i && grep ($_ eq $last_command, @{$Config{"pagers"}}) ||
   983         $Config{"suppress_terminal"}=~ /^y/i && grep ($_ eq $last_command, @{$Config{"terminal"}})
   984             )) {
   985             my $output = $cl->{short_output};
   986             if ($output) {
   987                  $output =~ s/^/         |/mg;
   988             }
   989             $this_day_result .= $output;
   990         }
   992 # DIFF
   993         if ( $Config{"show_diffs"} =~ /^y/i && $cl->{"diff"}) {
   994             my $diff = $cl->{"diff"};
   995             $diff =~ s/^/         |/mg;
   996             $this_day_result .= $diff;
   997         };
   998 # SHOT
   999         if ($Config{"show_screenshots"} =~ /^y/i && $cl->{"screenshot"}) {
  1000             $this_day_result .= "         #l3: screenshot=".$cl->{'screenshot'}."\n";
  1001         }
  1003 #NOTES
  1004         if ( $Config{"show_notes"} =~ /^y/i && $cl->{"note"}) {
  1005             my $note=$cl->{"note"};
  1006             $note =~ s/\n/\n#^/msg;
  1007             $this_day_result .= "#^ == ".$cl->{note_title}." ==\n" if $cl->{note_title};
  1008             $this_day_result .= "#^ ".$note."\n";
  1009         }
  1011     }
  1012     last: {
  1013         $result .= "== ".$Day_Name[$last_wday]." == \n";
  1014         $result .= $this_day_result;
  1015    }
  1017    return $result;
  1021 }
  1023 #############
  1024 # print_edit_all_html
  1025 #
  1026 # Вывести страницу с текстовым представлением журнала для редактирования
  1027 #
  1028 # In:       $_[0]       output_filename
  1029 # Out:
  1031 sub print_edit_all_html
  1032 {
  1033     my $output_filename= shift;
  1034     my $result;
  1035     my $cursor_position = 0;
  1037     $result = print_command_lines_txt;
  1039     $result = 
  1040                "<html>"
  1041                 ."<head>"
  1042                 ."<meta content='text/html; charset=utf-8' http-equiv='Content-Type' />"
  1043                 ."<link rel='stylesheet' href='$Config{frontend_css}' type='text/css'/>"
  1044                 ."<title>$title</title>"
  1045                 ."</head>"
  1046               ."<script>"
  1047               .$SetCursorPosition_JS
  1048               ."</script>"
  1049               ."<body onLoad='setCursorPosition(document.all.mytextarea, $cursor_position, $cursor_position+10)'>"
  1050               ."<h1>Журнал лабораторных работ. Правка</h1>"
  1051               ."<form>"
  1052               ."<textarea rows='30' cols='100' wrap='off' id='mytextarea'>$result</textarea>"
  1053               ."<br/><input type='submit' value='Сохранить' label='label'/>"
  1054               ."</form>"
  1055               ."<p>Внимательно правим, потом сохраняем</p>"
  1056               ."<p>Строки, начинающиеся символами #l3: можно трогать, только если точно знаешь, что делаешь</p>"
  1057               ."</body>"
  1058               ."</html>";
  1060     if ($output_filename eq "-") {
  1061         print $result;
  1062     }
  1063     else {
  1064         open(OUT, ">", $output_filename)
  1065             or die "Can't open $output_filename for writing\n";
  1066         binmode ":utf8";
  1067         print OUT "$result";
  1068         close(OUT);
  1069     }
  1070 }
  1072 #############
  1073 # print_all_txt
  1074 #
  1075 # Вывести страницу с текстовым представлением журнала для редактирования
  1076 #
  1077 # In:       $_[0]       output_filename
  1078 # Out:
  1080 sub print_all_txt
  1081 {
  1082     my $result;
  1084     $result = print_command_lines_txt;
  1086     $result =~ s/>/>/g;
  1087     $result =~ s/</</g;
  1088     $result =~ s/&/&/g;
  1090     if ($output_filename eq "-") {
  1091         print $result;
  1092     }
  1093     else {
  1094         open(OUT, ">:utf8", $output_filename)
  1095             or die "Can't open $output_filename for writing\n";
  1096         print OUT "$result";
  1097         close(OUT);
  1098     }
  1099 }
  1102 #############
  1103 # print_all_html
  1104 #
  1105 #
  1106 #
  1107 # In:       $_[0]       output_filename
  1108 # Out:
  1111 sub print_all_html
  1112 {
  1113     my $output_filename=$_[0];
  1115     my $result;
  1116     my ($command_lines,$toc)  = print_command_lines_html;
  1117     my $files_section         = print_files_html;
  1119     $result = print_header_html($toc);
  1122 #    $result.= join " <br/>", keys %Sessions;
  1123 #    for my $sess (keys %Sessions) {
  1124 #            $result .= join " ", keys (%{$Sessions{$sess}});
  1125 #            $result .= "<br/>";
  1126 #    }
  1128     $result.= "<h2 id='log'>Журнал</h2>"       . $command_lines;
  1129     $result.= "<h2 id='files'>Файлы</h2>"      . $files_section if $files_section;
  1130     $result.= "<h2 id='stat'>Статистика</h2>"  . print_stat_html;
  1131     $result.= "<h2 id='help'>Справка</h2>"     . $Html_Help . "<br/>"; 
  1132     $result.= "<h2 id='about'>О программе</h2>". $Html_About. "<br/>"; 
  1133     $result.= print_footer_html;
  1135     if ($output_filename eq "-") {
  1136         binmode STDOUT, ":utf8";
  1137         print $result;
  1138     }
  1139     else {
  1140         open(OUT, ">:utf8", $output_filename)
  1141             or die "Can't open $output_filename for writing\n";
  1142         print OUT $result;
  1143         close(OUT);
  1144     }
  1145 }
  1147 #############
  1148 # print_header_html
  1149 #
  1150 #
  1151 #
  1152 # In:   $_[0]       Содержание
  1153 # Out:              Распечатанный заголовок
  1155 sub print_header_html
  1156 {
  1157     my $toc = $_[0];
  1158     my $course_name = $Config{"course-name"};
  1159     my $course_code = $Config{"course-code"};
  1160     my $course_date = $Config{"course-date"};
  1161     my $course_center = $Config{"course-center"};
  1162     my $course_trainer = $Config{"course-trainer"};
  1163     my $course_student = $Config{"course-student"};
  1165     my $title    = "Журнал лабораторных работ";
  1166     $title      .= " -- ".$course_student if $course_student;
  1167     if ($course_date) {
  1168         $title  .= " -- ".$course_date; 
  1169         $title  .= $course_code ? "/".$course_code 
  1170                                 : "";
  1171     }
  1172     else {
  1173         $title  .= " -- ".$course_code if $course_code;
  1174     }
  1176     # Управляющая форма
  1177     my $control_form .= "<div class='visibility_form' title='Выберите какие элементы должны быть показаны в журнале'>"
  1178                      .  "<span class='header'>Видимые элементы</span>"
  1179                      .  "<span class='window_controls'><a href='' onclick='' title='свернуть форму управления'>_</a> <a href='' onclick='' title='закрыть форму управления'>x</a></span>"
  1180                      .  "<div><form>\n";
  1181     for my $element (sort keys %Elements_Visibility)
  1182     {
  1183         my ($skip, @e) = split /\s+/, $element;
  1184         my $showhide = join "", map { "ShowHide('$_');" } @e ;
  1185         $control_form .= "<div><input type='checkbox' name='$e[0]' onclick=\"$showhide\" checked>".
  1186                 $Elements_Visibility{$element}.
  1187                 "</input></div>";
  1188     }
  1189     $control_form .= "</form>\n"
  1190                   .  "</div>\n";
  1192     my $result;
  1193     $result = <<HEADER;
  1194     <html>
  1195     <head>
  1196     <meta content='text/html; charset=utf-8' http-equiv='Content-Type' />
  1197     <link rel='stylesheet' href='$Config{frontend_css}' type='text/css'/>
  1198     <title>$title</title>
  1199     </head>
  1200     <body>
  1201     <script>
  1202     $Html_JavaScript
  1203     </script>
  1205 <!-- vvv Tigra Hints vvv -->
  1206 <script language="JavaScript" src="/tigra/hints.js"></script>
  1207 <script language="JavaScript" src="/tigra/hints_cfg.js"></script>
  1208 <style>
  1209 /* a class for all Tigra Hints boxes, TD object */
  1210     .hintsClass
  1211         {text-align: center; font-family: Verdana, Arial, Helvetica; padding: 0px 0px 0px 0px;}
  1212 /* this class is used by Tigra Hints wrappers */
  1213     .row
  1214         {background: white;}
  1215 </style>
  1216 <!-- ^^^ Tigra Hints ^^^ -->
  1219     <div class='edit_link'>
  1220     [ <a href='?action=edit&$filter_url'>править</a> ]
  1221     </div>
  1222     <h1 onmouseover="myHint.show('1')" onmouseout="myHint.hide()" class='lined_header'>Журнал лабораторных работ</h1>
  1223 HEADER
  1224     if (    $course_student 
  1225             || $course_trainer 
  1226             || $course_name 
  1227             || $course_code 
  1228             || $course_date 
  1229             || $course_center) {
  1230             $result .= "<p>";
  1231             $result .= "Выполнил $course_student<br/>"  if $course_student;
  1232             $result .= "Проверил $course_trainer <br/>" if $course_trainer;
  1233             $result .= "Курс "                          if $course_name 
  1234                                                             || $course_code 
  1235                                                             || $course_date;
  1236             $result .= "$course_name "                  if $course_name;
  1237             $result .= "($course_code)"                 if $course_code;
  1238             $result .= ", $course_date<br/>"            if $course_date;
  1239             $result .= "Учебный центр $course_center <br/>" if $course_center;
  1240             $result .= "Фильтр ".join(" ", map("$filter{$_}=$_", keys %filter))."<br/>" if %filter;
  1241             $result .= "</p>";
  1242     }
  1244     $result .= <<HEADER;
  1245     <table width='100%'>
  1246     <tr>
  1247     <td width='*'>
  1249     <table border=0 id='toc' class='toc'>
  1250     <tr>
  1251     <td>
  1252     <div class='toc_title'>Содержание</div>
  1253     <ul>
  1254         <li><a href='#log'>Журнал</a></li>
  1255         <ul>$toc</ul>
  1256         <li><a href='#files'>Файлы</a></li>
  1257         <li><a href='#stat'>Статистика</a></li>
  1258         <li><a href='#help'>Справка</a></li>
  1259         <li><a href='#about'>О программе</a></li>
  1260     </ul>
  1261     </td>
  1262     </tr>
  1263     </table>
  1265     </td>
  1266     <td valign='top' width=200>$control_form</td>
  1267     </tr>
  1268     </table>
  1269 HEADER
  1271     return $result;
  1272 }
  1275 #############
  1276 # print_footer_html
  1277 #
  1278 #
  1279 #
  1280 #
  1281 #
  1283 sub print_footer_html
  1284 {
  1285     return "</body>\n</html>\n";
  1286 }
  1291 #############
  1292 # print_stat_html
  1293 #
  1294 #
  1295 #
  1296 # In:
  1297 # Out:
  1299 sub print_stat_html
  1300 {
  1301     %StatNames = (
  1302         FirstCommand        => "Время первой команды журнала",
  1303         LastCommand         => "Время последней команды журнала",
  1304         TotalCommands       => "Количество командных строк в журнале",
  1305         ErrorsPercentage    => "Процент команд с ненулевым кодом завершения, %",
  1306         MistypesPercentage  => "Процент синтаксически неверно набранных команд, %",
  1307         TotalTime           => "Суммарное время работы с терминалом <sup><font size='-2'>*</font></sup>, час",
  1308         CommandsPerTime     => "Количество командных строк в единицу времени, команда/мин",
  1309         CommandsFrequency   => "Частота использования команд",
  1310         RareCommands        => "Частота использования этих команд < 0.5%",
  1311     );
  1312     @StatOrder = (
  1313         FirstCommand,
  1314         LastCommand,
  1315         TotalCommands,
  1316         ErrorsPercentage,
  1317         MistypesPercentage,
  1318         TotalTime,
  1319         CommandsPerTime,
  1320         CommandsFrequency,
  1321         RareCommands,
  1322     );
  1324     # Подготовка статистики к выводу
  1325     # Некоторые значения пересчитываются!
  1326     # Дальше их лучше уже не использовать!!!
  1328     my %CommandsFrequency = %frequency_of_command;
  1330     $Stat{TotalTime} ||= 0;
  1331     my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($Stat{FirstCommand} || 0);
  1332     $Stat{FirstCommand} = sprintf "%02i:%02i:%02i %04i-%2i-%2i", $hour, $min, $sec,  $year+1900, $mon+1, $mday;
  1333     ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($Stat{LastCommand} || 0);
  1334     $Stat{LastCommand} = sprintf "%02i:%02i:%02i %04i-%2i-%2i", $hour, $min, $sec,  $year+1900, $mon+1, $mday;
  1335     if ($Stat{TotalCommands}) {
  1336         $Stat{ErrorsPercentage} = sprintf "%5.2f", $Stat{ErrorCommands}*100/$Stat{TotalCommands};
  1337         $Stat{MistypesPercentage} = sprintf "%5.2f", $Stat{MistypedCommands}*100/$Stat{TotalCommands};
  1338     }
  1339     $Stat{CommandsPerTime} = sprintf "%5.2f", $Stat{TotalCommands}*60/$Stat{TotalTime}
  1340         if $Stat{TotalTime};
  1341     $Stat{TotalTime} = sprintf "%5.2f", $Stat{TotalTime}/60/60;
  1343     my $total_commands=0;
  1344     for $command (keys %CommandsFrequency){
  1345         $total_commands += $CommandsFrequency{$command};
  1346     }
  1347     if ($total_commands) {
  1348         for $command (reverse sort {$CommandsFrequency{$a} <=> $CommandsFrequency{$b}} keys %CommandsFrequency){
  1349             my $command_html;
  1350             my $percentage = sprintf "%5.2f",$CommandsFrequency{$command}*100/$total_commands;
  1351             if ($percentage < 0.5) {
  1352                 my $hint = make_comment($command);
  1353                 $command_html = "$command";
  1354                 $command_html = "<span title='$hint' class='with_hint'>$command_html</span>" if $hint;
  1355                 $command_html = "<span class='without_hint'>$command_html</span>" if not $hint;
  1356                 my $command_html = "<tt>$command_html</tt>";
  1357                 $Stat{RareCommands} .= $command_html."<sub><font size='-2'>".$CommandsFrequency{$command}."</font></sub> , ";
  1358             }
  1359             else {
  1360                 my $hint = make_comment($command);
  1361                 $command_html = "$command";
  1362                 $command_html = "<span title='$hint' class='with_hint'>$command_html</span>" if $hint;
  1363                 $command_html = "<span class='without_hint'>$command_html</span>" if not $hint;
  1364                 my $command_html = "<tt>$command_html</tt>";
  1365                 $percentage = sprintf "%5.2f",$percentage;
  1366                 $Stat{CommandsFrequency} .= "<tr><td>".$command_html."</td><td>".$CommandsFrequency{$command}."</td>".
  1367                     "<td>|".("="x int($CommandsFrequency{$command}*100/$total_commands))."| $percentage%</td></tr>";
  1368             }
  1369         }
  1370         $Stat{CommandsFrequency} = "<table>".$Stat{CommandsFrequency}."</table>";
  1371         $Stat{RareCommands} =~ s/, $// if $Stat{RareCommands};
  1372     }
  1374     my $result = q();
  1375     for my $stat (@StatOrder) {
  1376         next unless $Stat{"$stat"};
  1377         $result .= "<tr valign='top'><td width='300'>".$StatNames{"$stat"}."</td><td>".$Stat{"$stat"}."</td></tr>"
  1378     }
  1379     $result  = "<table>$result</table>"
  1380              . "<font size='-2'>____<br/>*) Интервалы неактивности длительностью "
  1381              .  ($Config{stat_inactivity_interval}/60)
  1382              . " минут и более не учитываются</font></br>";
  1384     return $result;
  1385 }
  1388 sub collapse_list($)
  1389 {
  1390     my $res = "";
  1391     for my $elem (@{$_[0]}) {
  1392         if (ref $elem eq "ARRAY") {
  1393             $res .= "<ul>".collapse_list($elem)."</ul>";
  1394         }
  1395         else
  1396         {
  1397             $res .= "<li>".$elem."</li>";
  1398         }
  1399     }
  1400     return $res;
  1401 }
  1404 sub print_files_html
  1405 {
  1406     my $result = qq(); 
  1407     my @toc;
  1408     for my $file (sort keys %Files) {
  1409           my $div_id = "file:$file";
  1410           $div_id =~ s@/@_@g;
  1411           push @toc, "<a href='#$div_id'>$file</a>";
  1412           $result .= "<div class='filename' id='$div_id'>".$file."</div>\n"
  1413                   .  "<div class='file_navigation'><a href='#command:".$Files{$file}->{source_command_id}."'>".">"."</a></div>"
  1414                   .  "<div class='filedata'><pre>".$Files{$file}->{content}."</pre></div>";
  1415     }
  1416     if ($result) {
  1417         return "<div class='files_toc'>".collapse_list(\@toc)."</div>".$result;
  1418     } 
  1419     else {
  1420         return "";
  1421     }
  1422 }
  1425 sub init_variables
  1426 {
  1427 $Html_Help = <<HELP;
  1428     Для того чтобы использовать LiLaLo, не нужно знать ничего особенного:
  1429     всё происходит само собой.
  1430     Однако, чтобы ведение и последующее использование журналов
  1431     было как можно более эффективным, желательно иметь в виду следующее:
  1432     <ol>
  1433     <li><p> 
  1434     В журнал автоматически попадают все команды, данные в любом терминале системы.
  1435     </p></li>
  1436     <li><p>
  1437     Для того чтобы убедиться, что журнал на текущем терминале ведётся, 
  1438     и команды записываются, дайте команду w.
  1439     В поле WHAT, соответствующем текущему терминалу, 
  1440     должна быть указана программа script.
  1441     </p></li>
  1442     <li><p>
  1443     Команды, при наборе которых были допущены синтаксические ошибки, 
  1444     выводятся перечёркнутым текстом:
  1445 <table>
  1446 <tr class='command'>
  1447 <td class='script'>
  1448 <pre class='_mistyped_cline'>
  1449 \$ l s-l</pre>
  1450 <pre class='_mistyped_output'>bash: l: command not found
  1451 </pre>
  1452 </td>
  1453 </tr>
  1454 </table>
  1455 <br/>
  1456     </p></li>
  1457     <li><p>
  1458     Если код завершения команды равен нулю, 
  1459     команда была выполнена без ошибок.
  1460     Команды, код завершения которых отличен от нуля, выделяются цветом.
  1461 <table>
  1462 <tr class='command'>
  1463 <td class='script'>
  1464 <pre class='_wrong_cline'>
  1465 \$ test 5 -lt 4</pre>
  1466 </pre>
  1467 </td>
  1468 </tr>
  1469 </table>
  1470     Обратите внимание на то, что код завершения команды может быть отличен от нуля
  1471     не только в тех случаях, когда команда была выполнена с ошибкой.
  1472     Многие команды используют код завершения, например, для того чтобы показать результаты проверки
  1473 <br/>
  1474     </p></li>
  1475     <li><p>
  1476     Команды, ход выполнения которых был прерван пользователем, выделяются цветом.
  1477 <table>
  1478 <tr class='command'>
  1479 <td class='script'>
  1480 <pre class='_interrupted_cline'>
  1481 \$ find / -name abc</pre>
  1482 <pre class='interrupted_output'>find: /home/devi-orig/.gnome2: Keine Berechtigung
  1483 find: /home/devi-orig/.gnome2_private: Keine Berechtigung
  1484 find: /home/devi-orig/.nautilus/metafiles: Keine Berechtigung
  1485 find: /home/devi-orig/.metacity: Keine Berechtigung
  1486 find: /home/devi-orig/.inkscape: Keine Berechtigung
  1487 ^C
  1488 </pre>
  1489 </td>
  1490 </tr>
  1491 </table>
  1492 <br/>
  1493     </p></li>
  1494     <li><p>
  1495     Команды, выполненные с привилегиями суперпользователя,
  1496     выделяются слева красной чертой.
  1497 <table>
  1498 <tr class='command'>
  1499 <td class='script'>
  1500 <pre class='_root_cline'>
  1501 # id</pre>
  1502 <pre class='_root_output'>
  1503 uid=0(root) gid=0(root) Gruppen=0(root)
  1504 </pre>
  1505 </td>
  1506 </tr>
  1507 </table>
  1508     <br/>
  1509     </p></li>
  1510     <li><p>
  1511     Изменения, внесённые в текстовый файл с помощью редактора, 
  1512     запоминаются и показываются в журнале в формате ed.
  1513     Строки, начинающиеся символом "<", удалены, а строки,
  1514     начинающиеся символом ">" -- добавлены.
  1515 <table>
  1516 <tr class='command'>
  1517 <td class='script'>
  1518 <pre class='cline'>
  1519 \$ vi ~/.bashrc</pre>
  1520 <table><tr><td width='5'/><td class='diff'><pre>2a3,5
  1521 >    if [ -f /usr/local/etc/bash_completion ]; then
  1522 >         . /usr/local/etc/bash_completion
  1523 >        fi
  1524 </pre></td></tr></table></td>
  1525 </tr>
  1526 </table>
  1527     <br/>
  1528     </p></li>
  1529     <li><p>
  1530     Для того чтобы изменить файл в соответствии с показанными в диффшоте
  1531     изменениями, можно воспользоваться командой patch.
  1532     Нужно скопировать изменения, запустить программу patch, указав в
  1533     качестве её аргумента файл, к которому применяются изменения,
  1534     и всавить скопированный текст:
  1535 <table>
  1536 <tr class='command'>
  1537 <td class='script'>
  1538 <pre class='cline'>
  1539 \$ patch ~/.bashrc</pre>
  1540 </td>
  1541 </tr>
  1542 </table>
  1543     В данном случае изменения применяются к файлу ~/.bashrc
  1544     </p></li>
  1545     <li><p>
  1546     Для того чтобы получить краткую справочную информацию о команде, 
  1547     нужно подвести к ней мышь. Во всплывающей подсказке появится краткое
  1548     описание команды.
  1549     </p>
  1550     <p>
  1551     Если справочная информация о команде есть, 
  1552     команда выделяется голубым фоном, например: <span class="with_hint" title="главный текстовый редактор Unix">vi</span>.
  1553     Если справочная информация отсутствует,
  1554     команда выделяется розовым фоном, например: <span class="without_hint">notepad.exe</span>.
  1555     Справочная информация может отсутствовать в том случае, 
  1556     если (1) команда введена неверно; (2) если распознавание команды LiLaLo выполнено неверно;
  1557     (3) если информация о команде неизвестна LiLaLo.
  1558     Последнее возможно для редких команд.
  1559     </p></li>
  1560     <li><p>
  1561     Большие, в особенности многострочные, всплывающие подсказки лучше 
  1562     всего показываются браузерами KDE Konqueror, Apple Safari и Microsoft Internet Explorer.
  1563     В браузерах Mozilla и Firefox они отображаются не полностью, 
  1564     а вместо перевода строки выводится специальный символ.
  1565     </p></li>
  1566     <li><p>
  1567     Время ввода команды, показанное в журнале, соответствует времени 
  1568     <i>начала ввода командной строки</i>, которое равно тому моменту, 
  1569     когда на терминале появилось приглашение интерпретатора
  1570     </p></li>
  1571     <li><p>
  1572     Имя терминала, на котором была введена команда, показано в специальном блоке.
  1573     Этот блок показывается только в том случае, если терминал
  1574     текущей команды отличается от терминала предыдущей.
  1575     </p></li>
  1576     <li><p>
  1577     Вывод не интересующих вас в настоящий момент элементов журнала,
  1578     таких как время, имя терминала и других, можно отключить.
  1579     Для этого нужно воспользоваться <a href='#visibility_form'>формой управления журналом</a>
  1580     вверху страницы.
  1581     </p></li>
  1582     <li><p>
  1583     Небольшие комментарии к командам можно вставлять прямо из командной строки.
  1584     Комментарий вводится прямо в командную строку, после символов #^ или #v.
  1585     Символы ^ и v показывают направление выбора команды, к которой относится комментарий:
  1586     ^ - к предыдущей, v - к следующей.
  1587     Например, если в командной строке было введено:
  1588 <pre class='cline'>
  1589 \$ whoami
  1590 </pre>
  1591 <pre class='output'>
  1592 user
  1593 </pre>
  1594 <pre class='cline'>
  1595 \$ #^ Интересно, кто я?
  1596 </pre>
  1597     в журнале это будет выглядеть так:
  1599 <pre class='cline'>
  1600 \$ whoami
  1601 </pre>
  1602 <pre class='output'>
  1603 user
  1604 </pre>
  1605 <table class='note'><tr><td width='100%' class='note_text'>
  1606 <tr> <td> Интересно, кто я?<br/> </td></tr></table> 
  1607     </p></li>
  1608     <li><p>
  1609     Если комментарий содержит несколько строк,
  1610     его можно вставить в журнал следующим образом:
  1611 <pre class='cline'>
  1612 \$ whoami
  1613 </pre>
  1614 <pre class='output'>
  1615 user
  1616 </pre>
  1617 <pre class='cline'>
  1618 \$ cat > /dev/null #^ Интересно, кто я?
  1619 </pre>
  1620 <pre class='output'>
  1621 Программа whoami выводит имя пользователя, под которым 
  1622 мы зарегистрировались в системе.
  1623 -
  1624 Она не может ответить на вопрос о нашем назначении 
  1625 в этом мире.
  1626 </pre>
  1627     В журнале это будет выглядеть так:
  1628 <table>
  1629 <tr class='command'>
  1630 <td class='script'>
  1631 <pre class='cline'>
  1632 \$ whoami</pre>
  1633 <pre class='output'>user
  1634 </pre>
  1635 <table class='note'><tr><td class='note_title'>Интересно, кто я?</td></tr><tr><td width='100%' class='note_text'>
  1636 Программа whoami выводит имя пользователя, под которым<br/>
  1637 мы зарегистрировались в системе.<br/>
  1638 <br/>
  1639 Она не может ответить на вопрос о нашем назначении<br/>
  1640 в этом мире.<br/>
  1641 </td></tr></table>
  1642 </td>
  1643 </tr>
  1644 </table>
  1645     Для разделения нескольких абзацев между собой
  1646     используйте символ "-", один в строке.
  1647     <br/>
  1648 </p></li>
  1649     <li><p>
  1650     Комментарии, не относящиеся непосредственно ни к какой из команд, 
  1651     добавляются точно таким же способом, только вместо симолов #^ или #v 
  1652     нужно использовать символы #=
  1653     </p></li>
  1655     <p><li>
  1656     Содержимое файла может быть показано в журнале.
  1657     Для этого его нужно вывести с помощью программы cat.
  1658     Если вывод команды отметить симоволами #!, 
  1659     содержимое файла будет показано в журнале
  1660     в специально отведённой для этого секции.
  1661     </li></p>
  1663     <p>
  1664     <li>
  1665     Для того чтобы вставить скриншот интересующего вас окна в журнал,
  1666     нужно воспользоваться командой l3shot.
  1667     После того как команда вызвана, нужно с помощью мыши выбрать окно, которое
  1668     должно быть в журнале.
  1669     </li>
  1670     </p>
  1672     <p>
  1673     <li>
  1674     Команды в журнале расположены в хронологическом порядке.
  1675     Если две команды давались одна за другой, но на разных терминалах,
  1676     в журнале они будут рядом, даже если они не имеют друг к другу никакого отношения.
  1677 <pre>
  1678 1
  1679     2
  1680 3   
  1681     4
  1682 </pre>
  1683     Группы команд, выполненных на разных терминалах, разделяются специальной линией.
  1684     Под этой линией в правом углу показано имя терминала, на котором выполнялись команды.
  1685     Для того чтобы посмотреть команды только одного сенса, 
  1686     нужно щёкнуть по этому названию.
  1687     </li>
  1688     </p>
  1689 </ol>
  1690 HELP
  1692 $Html_About = <<ABOUT;
  1693     <p>
  1694     LiLaLo (L3) расшифровывается как Live Lab Log.<br/>
  1695     Программа разработана для повышения эффективности обучения Unix/Linux-системам.<br/>
  1696     (c) Игорь Чубин, 2004-2006<br/>
  1697     </p>
  1698 ABOUT
  1699 $Html_About.='$Id$ </p>';
  1701 $Html_JavaScript = <<JS;
  1702     function getElementsByClassName(Class_Name)
  1703     {
  1704         var Result=new Array();
  1705         var All_Elements=document.all || document.getElementsByTagName('*');
  1706         for (i=0; i<All_Elements.length; i++)
  1707             if (All_Elements[i].className==Class_Name)
  1708         Result.push(All_Elements[i]);
  1709         return Result;
  1710     }
  1711     function ShowHide (name)
  1712     {
  1713         elements=getElementsByClassName(name);
  1714         for(i=0; i<elements.length; i++)
  1715             if (elements[i].style.display == "none")
  1716                 elements[i].style.display = "";
  1717             else
  1718                 elements[i].style.display = "none";
  1719             //if (elements[i].style.visibility == "hidden")
  1720             //  elements[i].style.visibility = "visible";
  1721             //else
  1722             //  elements[i].style.visibility = "hidden";
  1723     }
  1724     function filter_by_output(text)
  1725     {
  1727         var jjj=0;
  1729         elements=getElementsByClassName('command');
  1730         for(i=0; i<elements.length; i++) {
  1731             subelems = elements[i].getElementsByTagName('pre');
  1732             for(j=0; j<subelems.length; j++) {
  1733                 if (subelems[j].className = 'output') {
  1734                     var str = new String(subelems[j].nodeValue);
  1735                     if (jjj != 1) { 
  1736                         alert(str);
  1737                         jjj=1;
  1738                     }
  1739                     if (str.indexOf(text) >0) 
  1740                         subelems[j].style.display = "none";
  1741                     else
  1742                         subelems[j].style.display = "";
  1744                 }
  1746             }
  1747         }       
  1749     }
  1750 JS
  1752 $SetCursorPosition_JS = <<JS;
  1753 function setCursorPosition(oInput,oStart,oEnd) {
  1754     oInput.focus();
  1755     if( oInput.setSelectionRange ) {
  1756         oInput.setSelectionRange(oStart,oEnd);
  1757     } else if( oInput.createTextRange ) {
  1758         var range = oInput.createTextRange();
  1759         range.collapse(true);
  1760         range.moveEnd('character',oEnd);
  1761         range.moveStart('character',oStart);
  1762         range.select();
  1763     }
  1764 }
  1765 JS
  1767 %Search_Machines = (
  1768         "google" =>     {   "query" =>  "http://www.google.com/search?q=" ,
  1769                     "icon"  =>  "$Config{frontend_google_ico}" },
  1770         "freebsd" =>    {   "query" =>  "http://www.freebsd.org/cgi/man.cgi?query=",
  1771                     "icon"  =>  "$Config{frontend_freebsd_ico}" },
  1772         "linux"  =>     {   "query" =>  "http://man.he.net/?topic=",
  1773                     "icon"  =>  "$Config{frontend_linux_ico}"},
  1774         "opennet"  =>   {   "query" =>  "http://www.opennet.ru/search.shtml?words=",
  1775                     "icon"  =>  "$Config{frontend_opennet_ico}"},
  1776         "local" =>  {   "query" =>  "http://www.freebsd.org/cgi/man.cgi?query=",
  1777                     "icon"  =>  "$Config{frontend_local_ico}" },
  1779     );
  1781 %Elements_Visibility = (
  1782         "0 new_commands_table"      =>  "новые команды",
  1783         "1 diff"      =>  "редактор",
  1784         "2 time"      =>  "время",
  1785         "3 ttychange"     =>  "терминал",
  1786         "4 wrong_output wrong_cline wrong_root_output wrong_root_cline" 
  1787                 =>  "команды с ненулевым кодом завершения",
  1788         "5 mistyped_output mistyped_cline mistyped_root_output mistyped_root_cline" 
  1789                 =>  "неверно набранные команды",
  1790         "6 interrupted_output interrupted_cline interrupted_root_output interrupted_root_cline" 
  1791                 =>  "прерванные команды",
  1792         "7 tab_completion_output tab_completion_cline"    
  1793                 =>  "продолжение с помощью tab"
  1794 );
  1796 @Day_Name      = qw/ Воскресенье Понедельник Вторник Среда Четверг Пятница Суббота /;
  1797 @Month_Name    = qw/ Январь Февраль Март Апрель Май Июнь Июль Август Сентябрь Октябрь Ноябрь Декабрь /;
  1798 @Of_Month_Name = qw/ Января Февраля Марта Апреля Мая Июня Июля Августа Сентября Октября Ноября Декабря /;
  1799 }
  1804 # Временно удалённый код
  1805 # Возможно, он не понадобится уже никогда
  1808 sub search_by
  1809 {
  1810     my $sm = shift;
  1811     my $topic = shift;
  1812     $topic =~ s/ /+/;
  1814     return "<a href='". $Search_Machines{$sm}->{"query"}."$topic'><img width='16' height='16' src='".
  1815                 $Search_Machines{$sm}->{"icon"}."' border='0'/></a>";
  1816 }
