lilalo
view l3-frontend @ 57:187b6636a3be
l3-agent:
Исправлен микробаг с uid
Раньше он не отправлялся в поток
l3-cgi:
При генерировании не CGI-версии
в таблице отсутствуют поля "инструктор" и "все"
На текущий момент они указывали в никуда,
поэтому я отключил их
l3-frontend:
Выводятся новые команды в начале каждого дня.
Команды сортируются по убыванию частоты использования.
l3scripts:
в письмо в одном месте е заменил на ё
Исправлен микробаг с uid
Раньше он не отправлялся в поток
l3-cgi:
При генерировании не CGI-версии
в таблице отсутствуют поля "инструктор" и "все"
На текущий момент они указывали в никуда,
поэтому я отключил их
l3-frontend:
Выводятся новые команды в начале каждого дня.
Команды сортируются по убыванию частоты использования.
l3scripts:
в письмо в одном месте е заменил на ё
| author | devi | 
|---|---|
| date | Wed Dec 28 18:44:42 2005 +0200 (2005-12-28) | 
| parents | 43aeb3036aaa | 
| children | 4d7e45bc659b | 
 line source
     1 #!/usr/bin/perl -w
     3 use IO::Socket;
     4 use lib '.';
     5 use l3config;
     6 use locale;
     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 # vvv Инициализация переменных выполняется процедурой init_variables
    16 our @Day_Name;
    17 our @Month_Name;
    18 our @Of_Month_Name;
    19 our %Search_Machines;
    20 our %Elements_Visibility;
    21 # ^^^
    23 our %Stat;
    24 our %CommandsFDistribution; # Сколько раз в журнале встречается какая команда
    26 my %mywi_cache_for;         # Кэш для экономии обращений к mywi
    28 sub make_comment;
    29 sub make_new_commands_table;
    30 sub load_command_lines_from_xml;
    31 sub load_sessions_from_xml;
    32 sub sort_command_lines;
    33 sub process_command_lines;
    34 sub init_variables;
    35 sub main;
    36 sub collapse_list($);
    38 sub print_all;
    39 sub print_command_lines;
    40 sub print_stat;
    41 sub print_header;
    42 sub print_footer;
    44 main();
    46 sub main
    47 {
    48     $| = 1;
    50     init_variables();
    51     init_config();
    53     open_mywi_socket();
    54     load_command_lines_from_xml($Config{"backend_datafile"});
    55     load_sessions_from_xml($Config{"backend_datafile"});
    56     sort_command_lines;
    57     process_command_lines;
    58     print_all($Config{"output"});
    59     close_mywi_socket;
    60 }
    62 # extract_from_cline
    64 # In:   $what       = commands | args
    65 # Out:  return      ссылка на хэш, содержащий результаты разбора
    66 #                   команда => позиция
    68 # Разобрать командную строку $_[1] и возвратить хэш, содержащий 
    69 # номер первого появление команды в строке:
    70 #   команда => первая позиция
    71 sub extract_from_cline
    72 {
    73     my $what = $_[0];
    74     my $cline = $_[1];
    75     my @lists = split /\;/, $cline;
    78     my @command_lines = ();
    79     for my $command_list (@lists) {
    80         push(@command_lines, split(/\|/, $command_list));
    81     }
    83     my %position_of_command;
    84     my %position_of_arg;
    85     my $i=0;
    86     for my $command_line (@command_lines) {
    87         $command_line =~ s@^\s*@@;
    88         $command_line =~ /\s*(\S+)\s*(.*)/;
    89         if ($1 && $1 eq "sudo" ) {
    90             $position_of_command{"$1"}=$i++;
    91             $command_line =~ s/\s*sudo\s+//;
    92         }
    93         if ($command_line !~ m@^\s*\S*/etc/@) {
    94             $command_line =~ s@^\s*\S+/@@;
    95         }
    97         $command_line =~ /\s*(\S+)\s*(.*)/;
    98         my $command = $1;
    99         my $args = $2;
   100         if ($command && !defined $position_of_command{"$command"}) {
   101                 $position_of_command{"$command"}=$i++;
   102         };  
   103         if ($args) {
   104             my @args = split (/\s+/, $args);
   105             for my $a (@args) {
   106                 $position_of_arg{"$a"}=$i++
   107                     if !defined $position_of_arg{"$a"};
   108             };  
   109         }
   110     }
   112     if ($what eq "commands") {
   113         return \%position_of_command;
   114     } else {
   115         return \%position_of_arg;
   116     }
   118 }
   123 #
   124 # Подпрограммы для работы с mywi
   125 #
   127 sub open_mywi_socket
   128 {
   129     $Mywi_Socket = IO::Socket::INET->new(
   130                 PeerAddr => $Config{mywi_server},
   131                 PeerPort => $Config{mywi_port},
   132                 Proto    => "tcp",
   133                 Type     => SOCK_STREAM);
   134 }
   136 sub close_mywi_socket
   137 {
   138     close ($Mywi_Socket) if $Mywi_Socket ;
   139 }
   142 sub mywi_client
   143 {
   144     my $query = $_[0];
   145     my $mywi;
   147     open_mywi_socket;
   148     if ($Mywi_Socket) {
   149         local $| = 1;
   150         local $/ = "";
   151         print $Mywi_Socket $query."\n";
   152         $mywi = <$Mywi_Socket>;
   153         $mywi = "" if $mywi =~ /nothing app/;
   154     }
   155     close_mywi_socket;
   156     return $mywi;
   157 }
   159 sub make_comment
   160 {
   161     my $cline = $_[0];
   162     #my $files = $_[1];
   164     my @comments;
   165     my @commands = keys %{extract_from_cline("commands", $cline)};
   166     my @args = keys %{extract_from_cline("args", $cline)};
   167     return if (!@commands && !@args);
   168     #return "commands=".join(" ",@commands)."; files=".join(" ",@files);
   170     # Commands
   171     for my $command (@commands) {
   172         $command =~ s/'//g;
   173         $CommandsFDistribution{$command}++;
   174         if (!$Commands_Description{$command}) {
   175             $mywi_cache_for{$command} ||= mywi_client ($command) || "";
   176             my $mywi = join ("\n", grep(/\([18]\)/, split(/\n/, $mywi_cache_for{$command})));
   177             $mywi =~ s/\s+/ /;
   178             if ($mywi !~ /^\s*$/) {
   179                 $Commands_Description{$command} = $mywi;
   180             }
   181             else {
   182                 next;
   183             }
   184         }
   186         push @comments, $Commands_Description{$command};
   187     }
   188     return join("
\n", @comments);
   190     # Files
   191     for my $arg (@args) {
   192         $arg =~ s/'//g;
   193         if (!$Args_Description{$arg}) {
   194             my $mywi;
   195             $mywi = mywi_client ($arg);
   196             $mywi = join ("\n", grep(/\([5]\)/, split(/\n/, $mywi)));
   197             $mywi =~ s/\s+/ /;
   198             if ($mywi !~ /^\s*$/) {
   199                 $Args_Description{$arg} = $mywi;
   200             }
   201             else {
   202                 next;
   203             }
   204         }
   206         push @comments, $Args_Description{$arg};
   207     }
   209 }
   211 =cut
   212 Процедура load_command_lines_from_xml выполняет загрузку разобранного lab-скрипта
   213 из XML-документа в переменную @Command_Lines
   215 # In:       $datafile           имя файла
   216 # Out:      @CommandLines       загруженные командные строки
   218 Предупреждение!
   219 Процедура не в состоянии обрабатывать XML-документ любой структуры.
   220 В действительности файл cache из которого загружаются данные 
   221 просто напоминает XML с виду.
   222 =cut
   223 sub load_command_lines_from_xml
   224 {
   225     my $datafile = $_[0];
   227     open (CLASS, $datafile)
   228         or die "Can't open file of the class ",$datafile,"\n";
   229     local $/;
   230     $data = <CLASS>;
   231     close(CLASS);
   233     for $command ($data =~ m@<command>(.*?)</command>@sg) {
   234         my %cl;
   235         while ($command =~ m@<([^>]*?)>(.*?)</\1>@sg) {
   236             $cl{$1} = $2;
   237         }
   238         push @Command_Lines, \%cl;
   239     }
   240 }
   242 sub load_sessions_from_xml
   243 {
   244     my $datafile = $_[0];
   246     open (CLASS, $datafile)
   247         or die "Can't open file of the class ",$datafile,"\n";
   248     local $/;
   249     my $data = <CLASS>;
   250     close(CLASS);
   252     for my $session ($data =~ m@<session>(.*?)</session>@sg) {
   253         my %session;
   254         while ($session =~ m@<([^>]*?)>(.*?)</\1>@sg) {
   255             $session{$1} = $2;
   256         }
   257         $Sessions{$session{local_session_id}} = \%session;
   258     }
   259 }
   262 # sort_command_lines
   263 # In:   @Command_Lines
   264 # Out:  @Command_Lies_Index
   266 sub sort_command_lines
   267 {
   269     my @index;
   270     for (my $i=0;$i<=$#Command_Lines;$i++) {
   271         $index[$i]=$i;
   272     }
   274     @Command_Lines_Index = sort {
   275         $Command_Lines[$index[$a]]->{"time"} <=> $Command_Lines[$index[$b]]->{"time"}
   276     } @index;
   278 }
   280 ##################
   281 # process_command_lines
   282 #
   283 # Обрабатываются командные строки @Command_Lines
   284 # Для каждой строки определяется:
   285 #   class   класс    
   286 #   note    комментарий 
   287 #
   288 # In:        @Command_Lines_Index
   289 # In-Out:    @Command_Lines
   291 sub process_command_lines
   292 {
   293     for my $i (@Command_Lines_Index) {
   294         my $cl = \$Command_Lines[$i];
   296         next if !$cl;
   298         $$cl->{err} ||=0;
   300         # Класс команды
   302         $$cl->{"class"} =   $$cl->{"err"} eq 130 ?  "interrupted"
   303                         :   $$cl->{"err"} eq 127 ?  "mistyped"
   304                         :   $$cl->{"err"}        ?  "wrong"
   305                         :                           "normal";
   307         if ($$cl->{"cline"} =~ /[^|`]\s*sudo/
   308             || $$cl->{"uid"} eq 0) {
   309             $$cl->{"class"}.="_root";
   310         }
   313 #Обработка пометок
   314 #  Если несколько пометок (notes) идут подряд, 
   315 #  они все объединяются
   317         if ($$cl->{cline}=~ m@cat[^#]*#([\^=v])\s*(.*)@) {
   319             my $note_operator = $1;
   320             my $note_title = $2;
   322             if ($note_operator eq "=") {
   323                 $$cl->{"class"} = "note";
   324                 $$cl->{"note"} = $$cl->{"output"};
   325                 $$cl->{"note_title"} = $2;
   326             }
   327             else {
   328                 my $j = $i;
   329                 if ($note_operator eq "^") {
   330                     $j--;
   331                     $j-- while ($j >=0  && (!$Command_Lines[$j] || $Command_Lines[$j]->{tty} ne $$cl->{tty}));
   332                 }
   333                 elsif ($note_operator eq "v") {
   334                     $j++;
   335                     $j++ while ($j <= @Command_Lines  && (!$Command_Lines[$j] || $Command_Lines[$j]->{tty} ne $$cl->{tty}));
   336                 }
   337                 $Command_Lines[$j]->{note_title}=$note_title;
   338                 $Command_Lines[$j]->{note}.=$$cl->{output};
   339                 $$cl=0;
   340             }
   341         }
   342         elsif ($$cl->{cline}=~ /#([\^=v])(.*)/) {
   344             my $note_operator = $1;
   345             my $note_text = $2;
   347             if ($note_operator eq "=") {
   348                 $$cl->{"class"} = "note";
   349                 $$cl->{"note"} = $note_text;
   350             }
   351             else {
   352                 my $j=$i;
   353                 if ($note_operator eq "^") {
   354                     $j--;
   355                     $j-- while ($j >=0  && (!$Command_Lines[$j] || $Command_Lines[$j]->{tty} ne $$cl->{tty}));
   356                 }
   357                 elsif ($note_operator eq "v") {
   358                     $j++;
   359                     $j++ while ($j <= @Command_Lines  && $Command_Lines[$j]->{tty} ne $$cl->{tty} || !$Command_Lines[$j]);
   360                 }
   361                 $Command_Lines[$j]->{note}.="$note_text\n";
   362                 $$cl=0;
   363             }
   364         }
   365     }   
   367 }
   370 =cut
   371 Процедура print_command_lines выводит HTML-представление
   372 разобранного lab-скрипта. 
   374 Разобранный lab-скрипт должен находиться в массиве @Command_Lines
   375 =cut
   377 sub print_command_lines
   378 {
   380     my @toc;                # Оглавление
   381     my $note_number=0;
   383     my $result = q();
   384     my $this_day_resut = q();
   386     my $cl;
   387     my $last_tty="";
   388     my $last_day=q();
   389     my $last_wday=q();
   390     my $in_range=0;
   392     my $current_command=0;
   394     my @known_commands;
   396     my %filter;
   398     if ($Config{filter}) {
   399         # Инициализация фильтра
   400         my %filter;
   401         for (split /&/,$Config{filter}) {
   402             my ($var, $val) = split /=/;
   403             $filter{$var} = $val || "";
   404         }
   405     }
   407     $Stat{LastCommand}   ||= 0;
   408     $Stat{TotalCommands} ||= 0;
   409     $Stat{ErrorCommands} ||= 0;
   410     $Stat{MistypedCommands} ||= 0;
   412 COMMAND_LINE:
   413     for my $k (@Command_Lines_Index) {
   415         my $cl=$Command_Lines[$Command_Lines_Index[$current_command++]];
   416         next unless $cl;
   418 # Пропускаем команды, с одинаковым временем
   419 # Это не совсем правильно.
   420 # Возможно, что это команды, набираемые с помощью <completion>
   421 # или запомненные с помощью <ctrl-c>
   423         next if $Stat{LastCommand} == $cl->{time};
   425 # Набираем статистику
   426 # Хэш %Stat
   428         $Stat{FirstCommand} = $cl->{time} unless $Stat{FirstCommand};
   429         if ($cl->{time} - $Stat{LastCommand} < $Config{stat_inactivity_interval}) {
   430             $Stat{TotalTime} += $cl->{time} - $Stat{LastCommand}
   431         }
   432         $Stat{LastCommand} = $cl->{time};
   433         $Stat{TotalCommands}++;
   435 # Пропускаем строки, которые противоречат фильтру
   436 # Если у нас недостаточно информации о том, подходит строка под  фильтр или нет, 
   437 # мы её выводим
   439         for my $filter_key (keys %filter) {
   440             next COMMAND_LINE if 
   441                 defined($cl->{local_session_id}) 
   442                 && defined($Sessions{$cl->{local_session_id}}->{$filter_key}) 
   443                 && $Sessions{$cl->{local_session_id}}->{$filter_key} ne $filter{$filter_key};
   444         }
   446 # Пропускаем строки, выходящие за границу "signature",
   447 # при условии, что границы указаны
   448 # Пропускаем неправильные/прерванные/другие команды
   449         if ($Config{"from"} && $cl->{"cline"} =~ /$Config{"signature"}\s*$Config{"from"}/) {
   450             $in_range=1;
   451             next;
   452         }
   453         if ($Config{"to"} && $cl->{"cline"} =~ /$Config{"signature"}\s*$Config{"to"}/) {
   454             $in_range=0;
   455             next;
   456         }
   457         next    if ($Config{"from"} && $Config{"to"}   && !$in_range) 
   458                 || ($Config{"skip_empty"} =~ /^y/i     && $cl->{"cline"} =~ /^\s*$/ )
   459                 || ($Config{"skip_wrong"} =~ /^y/i     && $cl->{"err"} != 0)
   460                 || ($Config{"skip_interrupted"} =~ /^y/i && $cl->{"err"} == 130);
   462         if ($cl->{class} eq "note") {
   463             my $note = $cl->{note};
   464             $note = join ("\n", map ("<p>$_</p>", split (/-\n/, $note)));
   465             $note =~ s@(http:[a-zA-Z.0-9/?\_%-]*)@<a href='$1'>$1</a>@g;
   466             $note =~ s@(www\.[a-zA-Z.0-9/?\_%-]*)@<a href='$1'>$1</a>@g;
   467             $this_day_result .= "<tr><td colspan='6'>"
   468                              .  "<h4 id='note$note_number'>".$cl->{note_title}."</h4>" if $cl->{note_title}
   469                              .  "".$note."<p/><p/></td></tr>";
   471             if ($cl->{note_title}) {
   472                 push @{$toc[@toc]},"<a href='#note$note_number'>".$cl->{note_title}."</a>";
   473                 $note_number++;
   474             }
   475             next;
   476         }
   479         my $output="";
   480 # Выводим <head_lines> верхних строк
   481 # и <tail_lines> нижних строк,
   482 # если эти параметры существуют
   484         my @lines = split '\n', $cl->{"output"};
   485         if (($Config{"head_lines"} || $Config{"tail_lines"})
   486              && $#lines >  $Config{"head_lines"} + $Config{"tail_lines"} ) {
   488             for (my $i=0; $i<= $#lines && $i < $Config{"head_lines"}; $i++) {
   489                 $output .= $lines[$i]."\n";
   490             }
   491             $output .= $Config{"skip_text"}."\n";
   493             my $start_line=$#lines-$Config{"tail_lines"}+1;
   494             for ($i=$start_line; $i<= $#lines; $i++) {
   495                 $output .= $lines[$i]."\n";
   496             }
   497         } 
   498         else {
   499             $output .= $cl->{"output"};
   500         }   
   502 #
   503 ##
   504 ## Начинается собственно вывод
   505 ##
   506 #
   508         my ($sec,$min,$hour,$day,$mon,$year,$wday,$yday,$isdst) = localtime($cl->{time});
   510         # Добавляем спереди 0 для удобочитаемости
   511         $min  = "0".$min  if $min  =~ /^.$/;
   512         $hour = "0".$hour if $hour =~ /^.$/;
   513         $sec  = "0".$sec  if $sec  =~ /^.$/;
   515         $class=$cl->{"class"};
   516         $Stat{ErrorCommands}++          if $class =~ /wrong/;
   517         $Stat{MistypedCommands}++       if $class =~ /mistype/;
   520 # DAY CHANGE
   521         if ( $last_day ne $day) {
   522             if ($last_day) {
   524 # Вычисляем разность множеств.
   525 # Что-то вроде этого, если бы так можно было писать:
   526 #   @new_commands = keys %CommandsFDistribution - @known_commands;
   529                 $result .= "<h3 id='day$last_day'>".$Day_Name[$last_wday]."</h3>";
   531                 my $new_commands_section = make_new_commands_table(\@known_commands);
   532                 @known_commands = keys %CommandsFDistribution;
   534                 if ($new_commands_section) {
   535                     $result .= "<h5>Новые команды</h5>"
   536                             .  "<table class='new_commands_table'>"
   537                             .  "<tr class='new_commands_header'><td>Команда</td><td>Описание</td></tr>"
   538                             .  $new_commands_section 
   539                             .  "</table>"
   540                 }
   542                 $result .= "<table width='100%'>\n";
   543                 $result .= $this_day_result;
   544                 $result .= "</table>";
   545             }
   547             push @toc, "<a href='#day$day'>".$Day_Name[$wday]."</a>\n";
   548             $last_day=$day;
   549             $last_wday=$wday;
   550             $this_day_result = q();
   551         }
   553         $this_day_result .= "<tr class='command'>\n";
   556 # CONSOLE CHANGE
   557         if ( $last_tty ne $cl->{"tty"}) {
   558             my $tty = $cl->{"tty"};
   559             $this_day_result .= "<td colspan='6'>"
   560                                 ."<table><tr><td class='ttychange' width='140' align='center'>"
   561                                 . $tty
   562                                 ."</td></tr></table>"
   563                                 ."</td></tr><tr>";
   564             $last_tty=$cl->{"tty"};
   565         }
   567 # TIME
   568         $this_day_result .= $Config{"show_time"} =~ /^y/i
   569                  ? "<td valign='top' class='time' width='$Config{time_width}'>$hour:$min:$sec</td>"
   570                  : "<td width='0'/>";
   572 # COMMAND
   573         my $hint = make_comment($cl->{"cline"});
   575         my $cline;
   576         $cline = $cl->{"prompt"}.$cl->{"cline"};
   577         $cline =~ s/\n//;
   579         $cline = "<span title='$hint' class='with_hint'>$cline</span>" if $hint;
   580         $cline = "<span class='without_hint'>$cline</span>" if !$hint;
   582         $this_day_result .= "<td class='script'>\n";
   583         $this_day_result .= "<pre class='${class}_cline'>\n" . $cline . "</pre>\n";
   585 # OUTPUT
   586         my $last_command = $cl->{"last_command"};
   587         if (!( 
   588         $Config{"suppress_editors"} =~ /^y/i && grep ($_ eq $last_command, @{$Config{"editors"}}) ||
   589         $Config{"suppress_pagers"}  =~ /^y/i && grep ($_ eq $last_command, @{$Config{"pagers"}}) ||
   590         $Config{"suppress_terminal"}=~ /^y/i && grep ($_ eq $last_command, @{$Config{"terminal"}})
   591             )) {
   592             $this_day_result .= "<pre class='".$class."_output'>" . $output . "</pre>\n";
   593         }   
   595 # DIFF
   596         if ( $Config{"show_diffs"} =~ /^y/i && $cl->{"diff"}) {
   597             $this_day_result .= "<table><tr><td width='5'/><td class='diff'><pre>"
   598                     .  $cl->{"diff"}
   599                     .  "</pre></td></tr></table>";
   600         }
   602 #NOTES
   603         if ( $Config{"show_notes"} =~ /^y/i && $cl->{"note"}) {
   604             my $note=$cl->{"note"};
   605             $note =~ s/\n/<br\/>\n/msg;
   606             if (not $note =~ s@(http:[a-zA-Z.0-9/_?%-]*)@<a href='$1'>$1</a>@g) {
   607               $note =~ s@(www\.[a-zA-Z.0-9/_?%-]*)@<a href='$1'>$1</a>@g;
   608             };
   609         #   Ширину пока не используем
   610         #   $this_day_result .= "<table width='$Config{note_width}' class='note'>";
   611             $this_day_result .= "<table class='note'>";
   612             $this_day_result .= "<tr><td class='note_title'>".$cl->{note_title}."</td></tr>" if $cl->{note_title};
   613             $this_day_result .= "<tr><td width='100%' class='note_text'>".$note."</td></tr>";
   614             $this_day_result .= "</table>\n";
   615         }
   617 # COMMENT
   618         if ( $Config{"show_comments"} =~ /^y/i) {
   619             my $comment = make_comment($cl->{"cline"});
   620             if ($comment) {
   621                 $this_day_result .= "<table width='$Config{comment_width}'><tr><td width='5'/><td>"
   622                         .  "<table class='note' width='100%'>"
   623                         .  $comment
   624                         .  "</table>\n"
   625                         .  "</td></tr></table>";
   626             }
   627         }
   629         # Вывод очередной команды окончен
   630         $this_day_result .= "</td>\n";
   631         $this_day_result .= "</tr>\n";
   632     }
   633     last: {
   634         my $new_commands_section = make_new_commands_table(\@known_commands);
   635         @known_commands = keys %CommandsFDistribution;
   637         $result .= "<h3 id='day$last_day'>".$Day_Name[$last_wday]."</h3>";
   638         if ($new_commands_section) {
   639             $result .= "<h5>Новые команды</h5>"
   640                     .  "<table class='new_commands_table'>"
   641                     .  "<tr class='new_commands_header'><td>Команда</td><td>Описание</td></tr>"
   642                     .  $new_commands_section 
   643                     .  "</table>"
   644         }
   646         $result .= "<table width='100%'>\n";
   647         $result .= $this_day_result;
   648         $result .= "</table>";
   649    }
   651     return ($result, collapse_list (\@toc));
   653 }
   655 sub make_new_commands_table
   656 {
   657     my @known_commands = @{$_[0]};
   659     my %count;
   660     my @new_commands = ();
   661     for my $c (keys %CommandsFDistribution, @known_commands) {
   662         $count{$c}++
   663     }
   664     for my $c (keys %CommandsFDistribution) {
   665         push @new_commands, $c if $count{$c} != 2;
   666     }
   669     my $new_commands_section;
   670     if (@new_commands){
   671         my $hint;
   672         for my $c (reverse sort { $CommandsFDistribution{$a} <=> $CommandsFDistribution{$b} } @new_commands) {
   673                 $hint = make_comment($c);
   674                 my ($command, $hint) = $hint =~ m/(.*?) \s*- \s*(.*)/;
   675                 $new_commands_section .= "<tr><td>$command</td><td>$hint</td></tr>"  if $hint;
   676         }
   677     }
   678     return $new_commands_section;
   679 }
   682 #############
   683 # print_all
   684 #
   685 #
   686 #
   687 # In:       $_[0]       output_filename
   688 # Out:
   691 sub print_all
   692 {
   693     my $output_filename=$_[0];
   695     my $result;
   696     my ($command_lines,$toc)  = print_command_lines;
   698     $result = print_header($toc);
   699     $result.= "<h2 id='log'>Журнал</h2>"       . $command_lines;
   700     $result.= "<h2 id='stat'>Статистика</h2>"  . print_stat;
   701     $result.= "<h2 id='help'>Справка</h2>"     . $Html_Help . "<br/>"; 
   702     $result.= "<h2 id='about'>О программе</h2>". $Html_About. "<br/>"; 
   703     $result.= print_footer;
   705     if ($output_filename eq "-") {
   706         print $result;
   707     }
   708     else {
   709         open(OUT, ">", $output_filename)
   710             or die "Can't open $output_filename for writing\n";
   711         print OUT $result;
   712         close(OUT);
   713     }
   714 }
   716 #############
   717 # print_header
   718 #
   719 #
   720 #
   721 # In:   $_[0]       Содержание
   722 # Out:              Распечатанный заголовок
   724 sub print_header
   725 {
   726     my $toc = $_[0];
   727     my $course_name = $Config{"course-name"};
   728     my $course_code = $Config{"course-code"};
   729     my $course_date = $Config{"course-date"};
   730     my $course_center = $Config{"course-center"};
   731     my $course_trainer = $Config{"course-trainer"};
   732     my $course_student = $Config{"course-student"};
   734     my $title    = "Журнал лабораторных работ";
   735     $title      .= " -- ".$course_student if $course_student;
   736     if ($course_date) {
   737         $title  .= " -- ".$course_date; 
   738         $title  .= $course_code ? "/".$course_code 
   739                                 : "";
   740     }
   741     else {
   742         $title  .= " -- ".$course_code if $course_code;
   743     }
   745     # Управляющая форма
   746     my $control_form .= "<table id='visibility_form' class='visibility_form'><tr><td>Видимые элементы</TD></tr><tr><td><form>\n";
   747     for my $element (keys %Elements_Visibility)
   748     {
   749         my @e = split /\s+/, $element;
   750         my $showhide = join "", map { "ShowHide('$_');" } @e ;
   751         $control_form .= "<input type='checkbox' name='$e[0]' onclick=\"$showhide\" checked>".
   752                 $Elements_Visibility{$element}.
   753                 "</input><br>\n";
   754     }
   755     $control_form .= "</form></td></tr></table>\n";
   757     my $result;
   758     $result = <<HEADER;
   759     <html>
   760     <head>
   761     <meta content='text/html; charset=utf-8' http-equiv='Content-Type' />
   762     <link rel='stylesheet' href='$Config{frontend_css}' type='text/css'/>
   763     <title>$title</title>
   764     </head>
   765     <body>
   766     <script>
   767     $Html_JavaScript
   768     </script>
   769     <h1>Журнал лабораторных работ</h1>
   770 HEADER
   771     if (    $course_student 
   772             || $course_trainer 
   773             || $course_name 
   774             || $course_code 
   775             || $course_date 
   776             || $course_center) {
   777             $result .= "<p>";
   778             $result .= "Выполнил $course_student<br/>"  if $course_student;
   779             $result .= "Проверил $course_trainer <br/>" if $course_trainer;
   780             $result .= "Курс "                          if $course_name 
   781                                                             || $course_code 
   782                                                             || $course_date;
   783             $result .= "$course_name "                  if $course_name;
   784             $result .= "($course_code)"                 if $course_code;
   785             $result .= ", $course_date<br/>"            if $course_date;
   786             $result .= "Учебный центр $course_center <br/>" if $course_center;
   787             $result .= "</p>";
   788     }
   790     $result .= <<HEADER;
   791     <table width='100%'>
   792     <tr>
   793     <td width='*'>
   795     <table border=0 id='toc' class='toc'>
   796     <tr>
   797     <td>
   798     <div class='toc_title'>Содержание</div>
   799     <ul>
   800         <li><a href='#log'>Журнал</a></li>
   801         <ul>$toc</ul>
   802         <li><a href='#stat'>Статистика</a></li>
   803         <li><a href='#help'>Справка</a></li>
   804         <li><a href='#about'>О программе</a></li>
   805     </ul>
   806     </td>
   807     </tr>
   808     </table>
   810     </td>
   811     <td valign='top' width=200>$control_form</td>
   812     </tr>
   813     </table>
   814 HEADER
   816     return $result;
   817 }
   820 #############
   821 # print_footer
   822 #
   823 #
   824 #
   825 #
   826 #
   828 sub print_footer
   829 {
   830     return "</body>\n</html>\n";
   831 }
   836 #############
   837 # print_stat
   838 #
   839 #
   840 #
   841 # In:
   842 # Out:
   844 sub print_stat
   845 {
   846     %StatNames = (
   847         FirstCommand        => "Время первой команды журнала",
   848         LastCommand         => "Время последней команды журнала",
   849         TotalCommands       => "Количество командных строк в журнале",
   850         ErrorsPercentage    => "Процент команд с ненулевым кодом завершения, %",
   851         MistypesPercentage  => "Процент синтаксически неверно набранных команд, %",
   852         TotalTime           => "Суммарное время работы с терминалом <sup><font size='-2'>*</font></sup>, час",
   853         CommandsPerTime     => "Количество командных строк в единицу времени, команда/мин",
   854         CommandsFrequency   => "Частота использования команд",
   855         RareCommands        => "Частота использования этих команд < 0.5%",
   856     );
   857     @StatOrder = (
   858         FirstCommand,
   859         LastCommand,
   860         TotalCommands,
   861         ErrorsPercentage,
   862         MistypesPercentage,
   863         TotalTime,
   864         CommandsPerTime,
   865         CommandsFrequency,
   866         RareCommands,
   867     );
   869     # Подготовка статистики к выводу
   870     # Некоторые значения пересчитываются!
   871     # Дальше их лучше уже не использовать!!!
   873     my %CommandsFrequency = %CommandsFDistribution;
   875     $Stat{TotalTime} ||= 0;
   876     my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($Stat{FirstCommand} || 0);
   877     $Stat{FirstCommand} = sprintf "%02i:%02i:%02i %04i-%2i-%2i", $hour, $min, $sec,  $year+1900, $mon+1, $mday;
   878     ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($Stat{LastCommand} || 0);
   879     $Stat{LastCommand} = sprintf "%02i:%02i:%02i %04i-%2i-%2i", $hour, $min, $sec,  $year+1900, $mon+1, $mday;
   880     if ($Stat{TotalCommands}) {
   881         $Stat{ErrorsPercentage} = sprintf "%5.2f", $Stat{ErrorCommands}*100/$Stat{TotalCommands};
   882         $Stat{MistypesPercentage} = sprintf "%5.2f", $Stat{MistypedCommands}*100/$Stat{TotalCommands};
   883     }
   884     $Stat{CommandsPerTime} = sprintf "%5.2f", $Stat{TotalCommands}*60/$Stat{TotalTime}
   885         if $Stat{TotalTime};
   886     $Stat{TotalTime} = sprintf "%5.2f", $Stat{TotalTime}/60/60;
   888     my $total_commands=0;
   889     for $command (keys %CommandsFrequency){
   890         $total_commands += $CommandsFrequency{$command};
   891     }
   892     if ($total_commands) {
   893         for $command (reverse sort {$CommandsFrequency{$a} <=> $CommandsFrequency{$b}} keys %CommandsFrequency){
   894             my $command_html;
   895             my $percentage = sprintf "%5.2f",$CommandsFrequency{$command}*100/$total_commands;
   896             if ($percentage < 0.5) {
   897                 my $hint = make_comment($command);
   898                 $command_html = "$command";
   899                 $command_html = "<span title='$hint' class='with_hint'>$command_html</span>" if $hint;
   900                 $command_html = "<span class='without_hint'>$command_html</span>" if not $hint;
   901                 my $command_html = "<tt>$command_html</tt>";
   902                 $Stat{RareCommands} .= $command_html."<sub><font size='-2'>".$CommandsFrequency{$command}."</font></sub> , ";
   903             }
   904             else {
   905                 my $hint = make_comment($command);
   906                 $command_html = "$command";
   907                 $command_html = "<span title='$hint' class='with_hint'>$command_html</span>" if $hint;
   908                 $command_html = "<span class='without_hint'>$command_html</span>" if not $hint;
   909                 my $command_html = "<tt>$command_html</tt>";
   910                 $percentage = sprintf "%5.2f",$percentage;
   911                 $Stat{CommandsFrequency} .= "<tr><td>".$command_html."</td><td>".$CommandsFrequency{$command}."</td>".
   912                     "<td>|".("="x int($CommandsFrequency{$command}*100/$total_commands))."| $percentage%</td></tr>";
   913             }
   914         }
   915         $Stat{CommandsFrequency} = "<table>".$Stat{CommandsFrequency}."</table>";
   916         $Stat{RareCommands} =~ s/, $// if $Stat{RareCommands};
   917     }
   919     my $result = q();
   920     for my $stat (@StatOrder) {
   921         next unless $Stat{"$stat"};
   922         $result .= "<tr valign='top'><td width='300'>".$StatNames{"$stat"}."</td><td>".$Stat{"$stat"}."</td></tr>"
   923     }
   924     $result  = "<table>$result</table>"
   925              . "<font size='-2'>____<br/>*) Интервалы неактивности длительностью "
   926              .  ($Config{stat_inactivity_interval}/60)
   927              . " минут и более не учитываются</font></br>";
   929     return $result;
   930 }
   933 sub collapse_list($)
   934 {
   935     my $res = "";
   936     for my $elem (@{$_[0]}) {
   937         if (ref $elem eq "ARRAY") {
   938             $res .= "<ul>".collapse_list($elem)."</ul>";
   939         }
   940         else
   941         {
   942             $res .= "<li>".$elem."</li>";
   943         }
   944     }
   945     return $res;
   946 }
   951 sub init_variables
   952 {
   953 $Html_Help = <<HELP;
   954     Для того чтобы использовать LiLaLo, не нужно знать ничего особенного:
   955     всё происходит само собой.
   956     Однако, чтобы ведение и последующее использование журналов
   957     было как можно более эффективным, желательно иметь в виду следующее:
   958     <ol>
   959     <li><p> 
   960     В журнал автоматически попадают все команды, данные в любом терминале системы.
   961     </p></li>
   962     <li><p>
   963     Для того чтобы убедиться, что журнал на текущем терминале ведётся, 
   964     и команды записываются, дайте команду w.
   965     В поле WHAT, соответствующем текущему терминалу, 
   966     должна быть указана программа script.
   967     </p></li>
   968     <li><p>
   969     Команды, при наборе которых были допущены синтаксические ошибки, 
   970     выводятся перечёркнутым текстом:
   971 <table>
   972 <tr class='command'>
   973 <td class='script'>
   974 <pre class='mistyped_cline'>
   975 \$ l s-l</pre>
   976 <pre class='mistyped_output'>bash: l: command not found
   977 </pre>
   978 </td>
   979 </tr>
   980 </table>
   981 <br/>
   982     </p></li>
   983     <li><p>
   984     Если код завершения команды равен нулю, 
   985     команда была выполнена без ошибок.
   986     Команды, код завершения которых отличен от нуля, выделяются цветом.
   987 <table>
   988 <tr class='command'>
   989 <td class='script'>
   990 <pre class='wrong_cline'>
   991 \$ test 5 -lt 4</pre>
   992 </pre>
   993 </td>
   994 </tr>
   995 </table>
   996     Обратите внимание на то, что код завершения команды может быть отличен от нуля
   997     не только в тех случаях, когда команда была выполнена с ошибкой.
   998     Многие команды используют код завершения, например, для того чтобы показать результаты проверки
   999 <br/>
  1000     </p></li>
  1001     <li><p>
  1002     Команды, ход выполнения которых был прерван пользователем, выделяются цветом.
  1003 <table>
  1004 <tr class='command'>
  1005 <td class='script'>
  1006 <pre class='interrupted_cline'>
  1007 \$ find / -name abc</pre>
  1008 <pre class='interrupted_output'>find: /home/devi-orig/.gnome2: Keine Berechtigung
  1009 find: /home/devi-orig/.gnome2_private: Keine Berechtigung
  1010 find: /home/devi-orig/.nautilus/metafiles: Keine Berechtigung
  1011 find: /home/devi-orig/.metacity: Keine Berechtigung
  1012 find: /home/devi-orig/.inkscape: Keine Berechtigung
  1013 ^C
  1014 </pre>
  1015 </td>
  1016 </tr>
  1017 </table>
  1018 <br/>
  1019     </p></li>
  1020     <li><p>
  1021     Команды, выполненные с привилегиями суперпользователя,
  1022     выделяются слева красной чертой.
  1023 <table>
  1024 <tr class='command'>
  1025 <td class='script'>
  1026 <pre class='_root_cline'>
  1027 # id</pre>
  1028 <pre class='_root_output'>
  1029 uid=0(root) gid=0(root) Gruppen=0(root)
  1030 </pre>
  1031 </td>
  1032 </tr>
  1033 </table>
  1034     <br/>
  1035     </p></li>
  1036     <li><p>
  1037     Изменения, внесённые в текстовый файл с помощью редактора, 
  1038     запоминаются и показываются в журнале в формате ed.
  1039     Строки, начинающиеся символом "<", удалены, а строки,
  1040     начинающиеся символом ">" -- добавлены.
  1041 <table>
  1042 <tr class='command'>
  1043 <td class='script'>
  1044 <pre class='cline'>
  1045 \$ vi ~/.bashrc</pre>
  1046 <table><tr><td width='5'/><td class='diff'><pre>2a3,5
  1047 >    if [ -f /usr/local/etc/bash_completion ]; then
  1048 >         . /usr/local/etc/bash_completion
  1049 >        fi
  1050 </pre></td></tr></table></td>
  1051 </tr>
  1052 </table>
  1053     <br/>
  1054     </p></li>
  1055     <li><p>
  1056     Для того чтобы изменить файл в соответствии с показанными в диффшоте
  1057     изменениями, можно воспользоваться командой patch.
  1058     Нужно скопировать изменения, запустить программу patch, указав в
  1059     качестве её аргумента файл, к которому применяются изменения,
  1060     и всавить скопированный текст:
  1061 <table>
  1062 <tr class='command'>
  1063 <td class='script'>
  1064 <pre class='cline'>
  1065 \$ patch ~/.bashrc</pre>
  1066 </td>
  1067 </tr>
  1068 </table>
  1069     В данном случае изменения применяются к файлу ~/.bashrc
  1070     </p></li>
  1071     <li><p>
  1072     Для того чтобы получить краткую справочную информацию о команде, 
  1073     нужно подвести к ней мышь. Во всплывающей подсказке появится краткое
  1074     описание команды.
  1075     </p>
  1076     <p>
  1077     Если справочная информация о команде есть, 
  1078     команда выделяется голубым фоном, например: <span class="with_hint" title="главный текстовый редактор Unix">vi</span>.
  1079     Если справочная информация отсутствует,
  1080     команда выделяется розовым фоном, например: <span class="without_hint">notepad.exe</span>.
  1081     Справочная информация может отсутствовать в том случае, 
  1082     если (1) команда введена неверно; (2) если распознавание команды LiLaLo выполнено неверно;
  1083     (3) если информация о команде неизвестна LiLaLo.
  1084     Последнее возможно для редких команд.
  1085     </p></li>
  1086     <li><p>
  1087     Большие, в особенности многострочные, всплывающие подсказки лучше 
  1088     всего показываются браузерами KDE Konqueror, Apple Safari и Microsoft Internet Explorer.
  1089     В браузерах Mozilla и Firefox они отображаются не полностью, 
  1090     а вместо перевода строки выводится специальный символ.
  1091     </p></li>
  1092     <li><p>
  1093     Время ввода команды, показанное в журнале, соответствует времени 
  1094     <i>начала ввода командной строки</i>, которое равно тому моменту, 
  1095     когда на терминале появилось приглашение интерпретатора
  1096     </p></li>
  1097     <li><p>
  1098     Имя терминала, на котором была введена команда, показано в специальном блоке.
  1099     Этот блок показывается только в том случае, если терминал
  1100     текущей команды отличается от терминала предыдущей.
  1101     </p></li>
  1102     <li><p>
  1103     Вывод не интересующих вас в настоящий момент элементов журнала,
  1104     таких как время, имя терминала и других, можно отключить.
  1105     Для этого нужно воспользоваться <a href='#visibility_form'>формой управления журналом</a>
  1106     вверху страницы.
  1107     </p></li>
  1108     <li><p>
  1109     Небольшие комментарии к командам можно вставлять прямо из командной строки.
  1110     Комментарий вводится прямо в командную строку, после символов #^ или #v.
  1111     Символы ^ и v показывают направление выбора команды, к которой относится комментарий:
  1112     ^ - к предыдущей, v - к следующей.
  1113     Например, если в командной строке было введено:
  1114 <pre class='cline'>
  1115 \$ whoami
  1116 </pre>
  1117 <pre class='output'>
  1118 user
  1119 </pre>
  1120 <pre class='cline'>
  1121 \$ #^ Интересно, кто я?
  1122 </pre>
  1123     в журнале это будет выглядеть так:
  1125 <pre class='cline'>
  1126 \$ whoami
  1127 </pre>
  1128 <pre class='output'>
  1129 user
  1130 </pre>
  1131 <table class='note'><tr><td width='100%' class='note_text'>
  1132 <tr> <td> Интересно, кто я?<br/> </td></tr></table> 
  1133     </p></li>
  1134     <li><p>
  1135     Если комментарий содержит несколько строк,
  1136     его можно вставить в журнал следующим образом:
  1137 <pre class='cline'>
  1138 \$ whoami
  1139 </pre>
  1140 <pre class='output'>
  1141 user
  1142 </pre>
  1143 <pre class='cline'>
  1144 \$ cat > /dev/null #^ Интересно, кто я?
  1145 </pre>
  1146 <pre class='output'>
  1147 Программа whoami выводит имя пользователя, под которым 
  1148 мы зарегистрировались в системе.
  1149 -
  1150 Она не может ответить на вопрос о нашем назначении 
  1151 в этом мире.
  1152 </pre>
  1153     В журнале это будет выглядеть так:
  1154 <table>
  1155 <tr class='command'>
  1156 <td class='script'>
  1157 <pre class='cline'>
  1158 \$ whoami</pre>
  1159 <pre class='output'>user
  1160 </pre>
  1161 <table class='note'><tr><td class='note_title'>Интересно, кто я?</td></tr><tr><td width='100%' class='note_text'>
  1162 Программа whoami выводит имя пользователя, под которым<br/>
  1163 мы зарегистрировались в системе.<br/>
  1164 <br/>
  1165 Она не может ответить на вопрос о нашем назначении<br/>
  1166 в этом мире.<br/>
  1167 </td></tr></table>
  1168 </td>
  1169 </tr>
  1170 </table>
  1171     Для разделения нескольких абзацев между собой
  1172     используйте символ "-", один в строке.
  1173     <br/>
  1174 </p></li>
  1175     <li><p>
  1176     Комментарии, не относящиеся непосредственно ни к какой из команд, 
  1177     добавляются точно таким же способом, только вместо симолов #^ или #v 
  1178     нужно использовать символы #=
  1179     </p></li>
  1180 </ol>
  1181 HELP
  1183 $Html_About = <<ABOUT;
  1184     <p>
  1185     LiLaLo (L3) расшифровывается как Live Lab Log.<br/>
  1186     Программа разработана для повышения эффективности обучения Unix/Linux-системам.<br/>
  1187     (c) Игорь Чубин, 2004-2005<br/>
  1188     </p>
  1189 ABOUT
  1190 $Html_About.='$Id$ </p>';
  1192 $Html_JavaScript = <<JS;
  1193     function getElementsByClassName(Class_Name)
  1194     {
  1195         var Result=new Array();
  1196         var All_Elements=document.all || document.getElementsByTagName('*');
  1197         for (i=0; i<All_Elements.length; i++)
  1198             if (All_Elements[i].className==Class_Name)
  1199         Result.push(All_Elements[i]);
  1200         return Result;
  1201     }
  1202     function ShowHide (name)
  1203     {
  1204         elements=getElementsByClassName(name);
  1205         for(i=0; i<elements.length; i++)
  1206             if (elements[i].style.display == "none")
  1207                 elements[i].style.display = "";
  1208             else
  1209                 elements[i].style.display = "none";
  1210             //if (elements[i].style.visibility == "hidden")
  1211             //  elements[i].style.visibility = "visible";
  1212             //else
  1213             //  elements[i].style.visibility = "hidden";
  1214     }
  1215     function filter_by_output(text)
  1216     {
  1218         var jjj=0;
  1220         elements=getElementsByClassName('command');
  1221         for(i=0; i<elements.length; i++) {
  1222             subelems = elements[i].getElementsByTagName('pre');
  1223             for(j=0; j<subelems.length; j++) {
  1224                 if (subelems[j].className = 'output') {
  1225                     var str = new String(subelems[j].nodeValue);
  1226                     if (jjj != 1) { 
  1227                         alert(str);
  1228                         jjj=1;
  1229                     }
  1230                     if (str.indexOf(text) >0) 
  1231                         subelems[j].style.display = "none";
  1232                     else
  1233                         subelems[j].style.display = "";
  1235                 }
  1237             }
  1238         }       
  1240     }
  1241 JS
  1243 %Search_Machines = (
  1244         "google" =>     {   "query" =>  "http://www.google.com/search?q=" ,
  1245                     "icon"  =>  "$Config{frontend_google_ico}" },
  1246         "freebsd" =>    {   "query" =>  "http://www.freebsd.org/cgi/man.cgi?query=",
  1247                     "icon"  =>  "$Config{frontend_freebsd_ico}" },
  1248         "linux"  =>     {   "query" =>  "http://man.he.net/?topic=",
  1249                     "icon"  =>  "$Config{frontend_linux_ico}"},
  1250         "opennet"  =>   {   "query" =>  "http://www.opennet.ru/search.shtml?words=",
  1251                     "icon"  =>  "$Config{frontend_opennet_ico}"},
  1252         "local" =>  {   "query" =>  "http://www.freebsd.org/cgi/man.cgi?query=",
  1253                     "icon"  =>  "$Config{frontend_local_ico}" },
  1255     );
  1257 %Elements_Visibility = (
  1258         "note"      =>  "замечания",
  1259         "diff"      =>  "редактор",
  1260         "time"      =>  "время",
  1261         "ttychange"     =>  "терминал",
  1262         "wrong_output wrong_cline wrong_root_output wrong_root_cline" 
  1263                 =>  "команды с ошибками",
  1264         "interrupted_output interrupted_cline interrupted_root_output interrupted_root_cline" 
  1265                 =>  "прерванные команды",
  1266         "tab_completion_output tab_completion_cline"    
  1267                 =>  "продолжение с помощью tab"
  1268 );
  1270 @Day_Name      = qw/ Воскресенье Понедельник Вторник Среда Четверг Пятница Суббота /;
  1271 @Month_Name    = qw/ Январь Февраль Март Апрель Май Июнь Июль Август Сентябрь Октябрь Ноябрь Декабрь /;
  1272 @Of_Month_Name = qw/ Января Февраля Марта Апреля Мая Июня Июля Августа Сентября Октября Ноября Декабря /;
  1273 }
  1278 # Временно удалённый код
  1279 # Возможно, он не понадобится уже никогда
  1282 sub search_by
  1283 {
  1284     my $sm = shift;
  1285     my $topic = shift;
  1286     $topic =~ s/ /+/;
  1288     return "<a href='". $Search_Machines{$sm}->{"query"}."$topic'><img width='16' height='16' src='".
  1289                 $Search_Machines{$sm}->{"icon"}."' border='0'/></a>";
  1290 }
