lilalo
view l3-frontend @ 87:c70be67ed3d4
Наведение порядка в коде.
Обработка чуть лучше отделена от представления.
+ добавлено три совета в документацию
Обработка чуть лучше отделена от представления.
+ добавлено три совета в документацию
| author | devi | 
|---|---|
| date | Tue Feb 28 13:11:26 2006 +0200 (2006-02-28) | 
| parents | 2cb912bff2ea | 
| children | 385499ec544a | 
 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;
    14 our %filter;
    16 our %Files;
    18 # vvv Инициализация переменных выполняется процедурой init_variables
    19 our @Day_Name;
    20 our @Month_Name;
    21 our @Of_Month_Name;
    22 our %Search_Machines;
    23 our %Elements_Visibility;
    24 # ^^^
    26 our %Stat;
    27 our %frequency_of_command; # Сколько раз в журнале встречается какая команда
    28 our $table_number=1;
    30 my %mywi_cache_for;         # Кэш для экономии обращений к mywi
    32 sub make_comment;
    33 sub make_new_entries_table;
    34 sub load_command_lines_from_xml;
    35 sub load_sessions_from_xml;
    36 sub sort_command_lines;
    37 sub process_command_lines;
    38 sub init_variables;
    39 sub main;
    40 sub collapse_list($);
    42 sub minutes_passed;
    44 sub print_all;
    45 sub print_command_lines;
    46 sub print_files;
    47 sub print_stat;
    48 sub print_header;
    49 sub print_footer;
    51 main();
    53 sub main
    54 {
    55     $| = 1;
    57     init_variables();
    58     init_config();
    59     $Config{frontend_ico_path}=$Config{frontend_css};
    60     $Config{frontend_ico_path}=~s@/[^/]*$@@;
    62     open_mywi_socket();
    63     load_command_lines_from_xml($Config{"backend_datafile"});
    64     load_sessions_from_xml($Config{"backend_datafile"});
    65     sort_command_lines;
    66     process_command_lines;
    67     print_all($Config{"output"});
    68     close_mywi_socket;
    69 }
    71 # extract_from_cline
    73 # In:   $what       = commands | args
    74 # Out:  return      ссылка на хэш, содержащий результаты разбора
    75 #                   команда => позиция
    77 # Разобрать командную строку $_[1] и возвратить хэш, содержащий 
    78 # номер первого появление команды в строке:
    79 #   команда => первая позиция
    80 sub extract_from_cline
    81 {
    82     my $what = $_[0];
    83     my $cline = $_[1];
    84     my @lists = split /\;/, $cline;
    87     my @command_lines = ();
    88     for my $command_list (@lists) {
    89         push(@command_lines, split(/\|/, $command_list));
    90     }
    92     my %position_of_command;
    93     my %position_of_arg;
    94     my $i=0;
    95     for my $command_line (@command_lines) {
    96         $command_line =~ s@^\s*@@;
    97         $command_line =~ /\s*(\S+)\s*(.*)/;
    98         if ($1 && $1 eq "sudo" ) {
    99             $position_of_command{"$1"}=$i++;
   100             $command_line =~ s/\s*sudo\s+//;
   101         }
   102         if ($command_line !~ m@^\s*\S*/etc/@) {
   103             $command_line =~ s@^\s*\S+/@@;
   104         }
   106         $command_line =~ /\s*(\S+)\s*(.*)/;
   107         my $command = $1;
   108         my $args = $2;
   109         if ($command && !defined $position_of_command{"$command"}) {
   110                 $position_of_command{"$command"}=$i++;
   111         };  
   112         if ($args) {
   113             my @args = split (/\s+/, $args);
   114             for my $a (@args) {
   115                 $position_of_arg{"$a"}=$i++
   116                     if !defined $position_of_arg{"$a"};
   117             };  
   118         }
   119     }
   121     if ($what eq "commands") {
   122         return \%position_of_command;
   123     } else {
   124         return \%position_of_arg;
   125     }
   127 }
   132 #
   133 # Подпрограммы для работы с mywi
   134 #
   136 sub open_mywi_socket
   137 {
   138     $Mywi_Socket = IO::Socket::INET->new(
   139                 PeerAddr => $Config{mywi_server},
   140                 PeerPort => $Config{mywi_port},
   141                 Proto    => "tcp",
   142                 Type     => SOCK_STREAM);
   143 }
   145 sub close_mywi_socket
   146 {
   147     close ($Mywi_Socket) if $Mywi_Socket ;
   148 }
   151 sub mywi_client
   152 {
   153     my $query = $_[0];
   154     my $mywi;
   156     open_mywi_socket;
   157     if ($Mywi_Socket) {
   158         local $| = 1;
   159         local $/ = "";
   160         print $Mywi_Socket $query."\n";
   161         $mywi = <$Mywi_Socket>;
   162         $mywi = "" if $mywi =~ /nothing app/;
   163     }
   164     close_mywi_socket;
   165     return $mywi;
   166 }
   168 sub make_comment
   169 {
   170     my $cline = $_[0];
   171     #my $files = $_[1];
   173     my @comments;
   174     my @commands = keys %{extract_from_cline("commands", $cline)};
   175     my @args = keys %{extract_from_cline("args", $cline)};
   176     return if (!@commands && !@args);
   177     #return "commands=".join(" ",@commands)."; files=".join(" ",@files);
   179     # Commands
   180     for my $command (@commands) {
   181         $command =~ s/'//g;
   182         $frequency_of_command{$command}++;
   183         if (!$Commands_Description{$command}) {
   184             $mywi_cache_for{$command} ||= mywi_client ($command) || "";
   185             my $mywi = join ("\n", grep(/\([18]|sh|script\)/, split(/\n/, $mywi_cache_for{$command})));
   186             $mywi =~ s/\s+/ /;
   187             if ($mywi !~ /^\s*$/) {
   188                 $Commands_Description{$command} = $mywi;
   189             }
   190             else {
   191                 next;
   192             }
   193         }
   195         push @comments, $Commands_Description{$command};
   196     }
   197     return join("
\n", @comments);
   199     # Files
   200     for my $arg (@args) {
   201         $arg =~ s/'//g;
   202         if (!$Args_Description{$arg}) {
   203             my $mywi;
   204             $mywi = mywi_client ($arg);
   205             $mywi = join ("\n", grep(/\([5]\)/, split(/\n/, $mywi)));
   206             $mywi =~ s/\s+/ /;
   207             if ($mywi !~ /^\s*$/) {
   208                 $Args_Description{$arg} = $mywi;
   209             }
   210             else {
   211                 next;
   212             }
   213         }
   215         push @comments, $Args_Description{$arg};
   216     }
   218 }
   220 =cut
   221 Процедура load_command_lines_from_xml выполняет загрузку разобранного lab-скрипта
   222 из XML-документа в переменную @Command_Lines
   224 # In:       $datafile           имя файла
   225 # Out:      @CommandLines       загруженные командные строки
   227 Предупреждение!
   228 Процедура не в состоянии обрабатывать XML-документ любой структуры.
   229 В действительности файл cache из которого загружаются данные 
   230 просто напоминает XML с виду.
   231 =cut
   232 sub load_command_lines_from_xml
   233 {
   234     my $datafile = $_[0];
   236     open (CLASS, $datafile)
   237         or die "Can't open file with xml lablog ",$datafile,"\n";
   238     local $/;
   239     $data = <CLASS>;
   240     close(CLASS);
   242     for $command ($data =~ m@<command>(.*?)</command>@sg) {
   243         my %cl;
   244         while ($command =~ m@<([^>]*?)>(.*?)</\1>@sg) {
   245             $cl{$1} = $2;
   246         }
   247         push @Command_Lines, \%cl;
   248     }
   249 }
   251 sub load_sessions_from_xml
   252 {
   253     my $datafile = $_[0];
   255     open (CLASS, $datafile)
   256         or die "Can't open file with xml lablog ",$datafile,"\n";
   257     local $/;
   258     my $data = <CLASS>;
   259     close(CLASS);
   261     my $i=0;
   262     for my $session ($data =~ m@<session>(.*?)</session>@msg) {
   263         my %session_hash;
   264         while ($session =~ m@<([^>]*?)>(.*?)</\1>@sg) {
   265             $session_hash{$1} = $2;
   266         }
   267         $Sessions{$session_hash{local_session_id}} = \%session_hash;
   268     }
   269 }
   272 # sort_command_lines
   273 # In:   @Command_Lines
   274 # Out:  @Command_Lies_Index
   276 sub sort_command_lines
   277 {
   279     my @index;
   280     for (my $i=0;$i<=$#Command_Lines;$i++) {
   281         $index[$i]=$i;
   282     }
   284     @Command_Lines_Index = sort {
   285         $Command_Lines[$index[$a]]->{"time"} <=> $Command_Lines[$index[$b]]->{"time"}
   286     } @index;
   288 }
   290 ##################
   291 # process_command_lines
   292 #
   293 # Обрабатываются командные строки @Command_Lines
   294 # Для каждой строки определяется:
   295 #   class   класс    
   296 #   note    комментарий 
   297 #
   298 # In:        @Command_Lines_Index
   299 # In-Out:    @Command_Lines
   301 sub process_command_lines
   302 {
   303     for my $i (@Command_Lines_Index) {
   304         my $cl = \$Command_Lines[$i];
   306         next if !$cl;
   308         $$cl->{id} = $$cl->{"time"};
   310         $$cl->{err} ||=0;
   312         # Класс команды
   314         $$cl->{"class"} =   $$cl->{"err"} eq 130 ?  "interrupted"
   315                         :   $$cl->{"err"} eq 127 ?  "mistyped"
   316                         :   $$cl->{"err"}        ?  "wrong"
   317                         :                           "normal";
   319         if ($$cl->{"cline"} && 
   320             $$cl->{"cline"} =~ /[^|`]\s*sudo/
   321             || $$cl->{"uid"} eq 0) {
   322             $$cl->{"class"}.="_root";
   323         }
   325 #        my $hint;
   326 #        $hint = make_comment($$cl->{"cline"});
   327 #        if ($hint) {
   328 #            $$cl->{hint} = $hint;
   329 #        }
   330         $$cl->{hint}="";
   332 # Выводим <head_lines> верхних строк
   333 # и <tail_lines> нижних строк,
   334 # если эти параметры существуют
   335         my $output="";
   337         if ($$cl->{"last_command"} eq "cat" && !$$cl->{"err"} && !($$cl->{"cline"} =~ /</)) {
   338             my $filename = $$cl->{"cline"};
   339             $filename =~ s/.*\s+(\S+)\s*$/$1/;
   340             $Files{$filename}->{"content"} = $$cl->{"output"};
   341            $Files{$filename}->{"source_command_id"} = $$cl->{"id"}
   342         }
   343         my @lines = split '\n', $$cl->{"output"};
   344         if ((
   345              $Config{"head_lines"} 
   346              || $Config{"tail_lines"}
   347              )
   348              && $#lines >  $Config{"head_lines"} + $Config{"tail_lines"} ) {
   349 #
   350             for (my $i=0; $i<= $#lines && $i < $Config{"head_lines"}; $i++) {
   351                 $output .= $lines[$i]."\n";
   352             }
   353             $output .= $Config{"skip_text"}."\n";
   355             my $start_line=$#lines-$Config{"tail_lines"}+1;
   356             for (my $i=$start_line; $i<= $#lines; $i++) {
   357                 $output .= $lines[$i]."\n";
   358             }
   359         } 
   360         else {
   361            $output = $$cl->{"output"};
   362         }
   363         $$cl->{short_output} = $output;
   365 #Обработка пометок
   366 #  Если несколько пометок (notes) идут подряд, 
   367 #  они все объединяются
   369         if ($$cl->{cline} =~ /l3shot/) {
   370                 if ($$cl->{output} =~ m@Screenshot is written to.*/(.*)\.xwd@) {
   371                     $$cl->{screenshot}="$1";
   372                 }
   373         }
   375         if ($$cl->{cline}=~ m@cat[^#]*#([\^=v])\s*(.*)@) {
   377             my $note_operator = $1;
   378             my $note_title = $2;
   380             if ($note_operator eq "=") {
   381                 $$cl->{"class"} = "note";
   382                 $$cl->{"note"} = $$cl->{"output"};
   383                 $$cl->{"note_title"} = $2;
   384             }
   385             else {
   386                 my $j = $i;
   387                 if ($note_operator eq "^") {
   388                     $j--;
   389                     $j-- while ($j >=0  && (!$Command_Lines[$j] || $Command_Lines[$j]->{tty} ne $$cl->{tty}));
   390                 }
   391                 elsif ($note_operator eq "v") {
   392                     $j++;
   393                     $j++ while ($j <= @Command_Lines  && (!$Command_Lines[$j] || $Command_Lines[$j]->{tty} ne $$cl->{tty}));
   394                 }
   395                 $Command_Lines[$j]->{note_title}=$note_title;
   396                 $Command_Lines[$j]->{note}.=$$cl->{output};
   397                 $$cl=0;
   398             }
   399         }
   400         elsif ($$cl->{cline}=~ /#([\^=v])(.*)/) {
   402             my $note_operator = $1;
   403             my $note_text = $2;
   405             if ($note_operator eq "=") {
   406                 $$cl->{"class"} = "note";
   407                 $$cl->{"note"} = $note_text;
   408             }
   409             else {
   410                 my $j=$i;
   411                 if ($note_operator eq "^") {
   412                     $j--;
   413                     $j-- while ($j >=0  && (!$Command_Lines[$j] || $Command_Lines[$j]->{tty} ne $$cl->{tty}));
   414                 }
   415                 elsif ($note_operator eq "v") {
   416                     $j++;
   417                     $j++ while ($j <= @Command_Lines  && $Command_Lines[$j]->{tty} ne $$cl->{tty} || !$Command_Lines[$j]);
   418                 }
   419                 $Command_Lines[$j]->{note}.="$note_text\n";
   420                 $$cl=0;
   421             }
   422         }
   423         if ($$cl->{"class"} == "note") {
   424                 my $note_html = $$cl->{note};
   425                 $note_html = join ("\n", map ("<p>$_</p>", split (/-\n/, $note)));
   426                 $note_html =~ s@(http:[a-zA-Z.0-9/?\_%-]*)@<a href='$1'>$1</a>@g;
   427                 $note_html =~ s@(www\.[a-zA-Z.0-9/?\_%-]*)@<a href='$1'>$1</a>@g;
   428                 $$cl->{"note_html"} = $note_html;
   429         }
   430     }   
   432 }
   435 =cut
   436 Процедура print_command_lines выводит HTML-представление
   437 разобранного lab-скрипта. 
   439 Разобранный lab-скрипт должен находиться в массиве @Command_Lines
   440 =cut
   442 sub print_command_lines
   443 {
   445     my @toc;                # Оглавление
   446     my $note_number=0;
   448     my $result = q();
   449     my $this_day_resut = q();
   451     my $cl;
   452     my $last_tty="";
   453     my $last_session="";
   454     my $last_day=q();
   455     my $last_wday=q();
   456     my $in_range=0;
   458     my $current_command=0;
   460     my @known_commands;
   463     if ($Config{filter}) {
   464         # Инициализация фильтра
   465         for (split /&/,$Config{filter}) {
   466             my ($var, $val) = split /=/;
   467             $filter{$var} = $val || "";
   468         }
   469     }
   471     $Stat{LastCommand}   ||= 0;
   472     $Stat{TotalCommands} ||= 0;
   473     $Stat{ErrorCommands} ||= 0;
   474     $Stat{MistypedCommands} ||= 0;
   476     my %new_entries_of = (
   477         "1 1"     =>   "программы пользователя",
   478         "2 8"     =>   "программы администратора",
   479         "3 sh"    =>   "команды интерпретатора",
   480         "4 script"=>   "скрипты",
   481     );
   483 COMMAND_LINE:
   484     for my $k (@Command_Lines_Index) {
   486         my $cl=$Command_Lines[$Command_Lines_Index[$current_command++]];
   487         next unless $cl;
   489 # Пропускаем команды, с одинаковым временем
   490 # Это не совсем правильно.
   491 # Возможно, что это команды, набираемые с помощью <completion>
   492 # или запомненные с помощью <ctrl-c>
   494         next if $Stat{LastCommand} == $cl->{time};
   496 # Пропускаем строки, которые противоречат фильтру
   497 # Если у нас недостаточно информации о том, подходит строка под  фильтр или нет, 
   498 # мы её выводим
   500         for my $filter_key (keys %filter) {
   501             next COMMAND_LINE 
   502                 if defined($cl->{local_session_id})
   503                 && defined($Sessions{$cl->{local_session_id}}->{$filter_key})
   504                 && $Sessions{$cl->{local_session_id}}->{$filter_key} ne $filter{$filter_key};
   505         }
   507 # Набираем статистику
   508 # Хэш %Stat
   510         $Stat{FirstCommand} = $cl->{time} unless $Stat{FirstCommand};
   511         if ($cl->{time} - $Stat{LastCommand} < $Config{stat_inactivity_interval}) {
   512             $Stat{TotalTime} += $cl->{time} - $Stat{LastCommand}
   513         }
   514         my $seconds_since_last_command = $cl->{time} - $Stat{LastCommand};
   516         if ($Stat{LastCommand} > $cl->{time}) {
   517                $result .= "Время идёт вспять<br/>";
   518         };
   519         $Stat{LastCommand} = $cl->{time};
   520         $Stat{TotalCommands}++;
   522 # Пропускаем строки, выходящие за границу "signature",
   523 # при условии, что границы указаны
   524 # Пропускаем неправильные/прерванные/другие команды
   525         if ($Config{"from"} && $cl->{"cline"} =~ /$Config{"signature"}\s*$Config{"from"}/) {
   526             $in_range=1;
   527             next;
   528         }
   529         if ($Config{"to"} && $cl->{"cline"} =~ /$Config{"signature"}\s*$Config{"to"}/) {
   530             $in_range=0;
   531             next;
   532         }
   533         next    if ($Config{"from"} && $Config{"to"}   && !$in_range) 
   534                 || ($Config{"skip_empty"} =~ /^y/i     && $cl->{"cline"} =~ /^\s*$/ )
   535                 || ($Config{"skip_wrong"} =~ /^y/i     && $cl->{"err"} != 0)
   536                 || ($Config{"skip_interrupted"} =~ /^y/i && $cl->{"err"} == 130);
   541 #
   542 ##
   543 ## Начинается собственно вывод
   544 ##
   545 #
   547 ### Сначала обрабатываем границы разделов
   548 ### Если тип команды "note", это граница
   550         if ($cl->{class} eq "note") {
   551             $this_day_result .= "<tr><td colspan='6'>"
   552                              .  "<h4 id='note$note_number'>".$cl->{note_title}."</h4>" if $cl->{note_title}
   553                              .  "".$cl->{note_html}."<p/><p/></td></tr>";
   555             if ($cl->{note_title}) {
   556                 push @{$toc[@toc]},"<a href='#note$note_number'>".$cl->{note_title}."</a>";
   557                 $note_number++;
   558             }
   559             next;
   560         }
   562         my ($sec,$min,$hour,$day,$mon,$year,$wday,$yday,$isdst) = localtime($cl->{time});
   564         # Добавляем спереди 0 для удобочитаемости
   565         $min  = "0".$min  if $min  =~ /^.$/;
   566         $hour = "0".$hour if $hour =~ /^.$/;
   567         $sec  = "0".$sec  if $sec  =~ /^.$/;
   569         $class=$cl->{"class"};
   570         $Stat{ErrorCommands}++          if $class =~ /wrong/;
   571         $Stat{MistypedCommands}++       if $class =~ /mistype/;
   573 # DAY CHANGE
   574         if ( $last_day ne $day) {
   575             if ($last_day) {
   577 # Вычисляем разность множеств.
   578 # Что-то вроде этого, если бы так можно было писать:
   579 #   @new_commands = keys %frequency_of_command - @known_commands;
   582                 $result .= "<h3 id='day$last_day'>".$Day_Name[$last_wday]."</h3>";
   583                 for my $entry_class (sort keys %new_entries_of) {
   584                     my $table_caption = "Таблица ".$table_number++.".".$Day_Name[$last_wday]
   585                                         .". Новые ".$new_entries_of{$entry_class};
   586                     my $new_commands_section = make_new_entries_table(
   587                                                 $table_caption, 
   588                                                 $entry_class=~/[0-9]+\s+(.*)/, 
   589                                                 \@known_commands);
   590                 }
   591                 @known_commands = keys %frequency_of_command;
   592                 $result .= $this_day_result;
   593             }
   595             push @toc, "<a href='#day$day'>".$Day_Name[$wday]."</a>\n";
   596             $last_day=$day;
   597             $last_wday=$wday;
   598             $this_day_result = q();
   599         }
   600         else {
   601             $this_day_result .= minutes_passed($seconds_since_last_command);
   602         }
   604         $this_day_result .= "<div class='command' id='command:".$cl->{"id"}."' >\n";
   606 # CONSOLE CHANGE
   607         if ($cl->{"tty"} && $last_tty ne $cl->{"tty"} && 0) {
   608             my $tty = $cl->{"tty"};
   609             $this_day_result .= "<div class='ttychange'>"
   610                                 . $tty
   611                                 ."</div>";
   612             $last_tty=$cl->{"tty"};
   613         }
   615 # Session change
   616         if ( $last_session ne $cl->{"local_session_id"}) {
   617             my $tty = $cl->{"tty"};
   618             $this_day_result .= "<div class='ttychange'><a href='?local_session_id=".$cl->{"local_session_id"}."'>"
   619                                 . $Sessions{$cl->{"local_session_id"}}->{"tty"}
   620                                 ."</a></div>";
   621             $last_session=$cl->{"local_session_id"};
   622         }
   624 # TIME
   625         if ($Config{"show_time"} =~ /^y/i) {
   626             $this_day_result .= "<div class='time'>$hour:$min:$sec</div>" 
   627         }
   629 # COMMAND
   630         my $cline;
   631         $prompt_hint = join ("
", map("$_=$cl->{$_}", grep (!/^(output|diff)$/, sort(keys(%{$cl})))));
   632         $cline = "<span title='$prompt_hint'>".$cl->{"prompt"}."</span>".$cl->{"cline"};
   633         $cline =~ s/\n//;
   635         if ($cl->{"hint"}) {
   636             $cline = "<span title='$cl->{hint}' class='with_hint'>$cline</span>" ;
   637         } 
   638         else {
   639             $cline = "<span class='without_hint'>$cline</span>";
   640         }
   642         $this_day_result .= "<table cellpadding='0' cellspacing='0'><tr><td>\n<div class='cblock_$cl->{class}'>\n";
   643         $this_day_result .= "<div class='cline'>\n" . $cline ;      #cline
   644         $this_day_result .= "<span title='Код завершения ".$cl->{"err"}."'>\n"
   645                          .  "<img src='".$Config{frontend_ico_path}."/error.png'/>\n"
   646                          .  "</span>\n" if $cl->{"err"};
   647         $this_day_result .= "</div>\n";                             #cline
   649 # OUTPUT
   650         my $last_command = $cl->{"last_command"};
   651         if (!( 
   652         $Config{"suppress_editors"} =~ /^y/i && grep ($_ eq $last_command, @{$Config{"editors"}}) ||
   653         $Config{"suppress_pagers"}  =~ /^y/i && grep ($_ eq $last_command, @{$Config{"pagers"}}) ||
   654         $Config{"suppress_terminal"}=~ /^y/i && grep ($_ eq $last_command, @{$Config{"terminal"}})
   655             )) {
   656             $this_day_result .= "<pre class='output'>\n" . $cl->{short_output} . "</pre>\n";
   657         }
   659 # DIFF
   660         $this_day_result .= "<pre class='diff'>".$cl->{"diff"}."</pre>"
   661             if ( $Config{"show_diffs"} =~ /^y/i && $cl->{"diff"});
   662 # SHOT
   663         $this_day_result .= "<img src='"
   664                 .$Config{l3shot_path}
   665                 .$cl->{"screenshot"}
   666                 .$Config{l3shot_suffix}
   667                 ."' alt ='screenshot id ".$cl->{"screenshot"}
   668                 ."'/>"
   669             if ( $Config{"show_screenshots"} =~ /^y/i && $cl->{"screenshot"});
   671 #NOTES
   672         if ( $Config{"show_notes"} =~ /^y/i && $cl->{"note"}) {
   673             my $note=$cl->{"note"};
   674             $note =~ s/\n/<br\/>\n/msg;
   675             if (not $note =~ s@(http:[a-zA-Z.0-9/_?%-]*)@<a href='$1'>$1</a>@g) {
   676               $note =~ s@(www\.[a-zA-Z.0-9/_?%-]*)@<a href='$1'>$1</a>@g;
   677             };
   678             $this_day_result .= "<div class='note'>";
   679             $this_day_result .= "<div class='note_title'>".$cl->{note_title}."</div>" if $cl->{note_title};
   680             $this_day_result .= "<div class='note_text'>".$note."</div>";
   681             $this_day_result .= "</div>\n";
   682         }
   684         # Вывод очередной команды окончен
   685         $this_day_result .= "</div>\n";                     # cblock
   686         $this_day_result .= "</td></tr></table>\n"
   687                          .  "</div>\n";                     # command
   688     }
   689     last: {
   690         $result .= "<h3 id='day$last_day'>".$Day_Name[$last_wday]."</h3>";
   692         for my $entry_class (keys %new_entries_of) {
   693             my $table_caption = "Таблица ".$table_number++.".".$Day_Name[$last_wday]
   694                               . ". Новые ".$new_entries_of{$entry_class};
   695             my $new_commands_section = make_new_entries_table(
   696                                         $table_caption, 
   697                                         $entry_class=~/[0-9]+\s+(.*)/, 
   698                                         \@known_commands);
   699         }
   700         @known_commands = keys %frequency_of_command;
   701         $result .= $this_day_result;
   702    }
   704     return ($result, collapse_list (\@toc));
   706 }
   708 #############
   709 # print_all
   710 #
   711 # Напечатать таблицу неизвестных команд
   712 #
   713 # In:       $_[0]       table_caption
   714 #           $_[1]       entries_class
   715 #           @_[2..]     known_commands
   716 # Out:
   718 sub make_new_entries_table
   719 {
   720     my $table_caption;
   721     my $entries_class = shift;
   722     my @known_commands = @{$_[0]};
   723     my $result = "";
   725     my %count;
   726     my @new_commands = ();
   727     for my $c (keys %frequency_of_command, @known_commands) {
   728         $count{$c}++
   729     }
   730     for my $c (keys %frequency_of_command) {
   731         push @new_commands, $c if $count{$c} != 2;
   732     }
   734     my $new_commands_section;
   735     if (@new_commands){
   736         my $hint;
   737         for my $c (reverse sort { $frequency_of_command{$a} <=> $frequency_of_command{$b} } @new_commands) {
   738                 $hint = make_comment($c);
   739                 next unless $hint;
   740                 my ($command, $hint) = $hint =~ m/(.*?) \s*- \s*(.*)/;
   741                 next unless $command =~ s/\($entries_class\)//i;
   742                 $new_commands_section .= "<tr><td valign='top'>$command</td><td>$hint</td></tr>";
   743         }
   744     }
   745     if ($new_commands_section) {
   746         $result .= "<table class='new_commands_table' width='700' cellspacing='0' cellpadding='0'>"
   747                 .  "<tr class='new_commands_caption'>"
   748                 .  "<td colspan='2' align='right'>$table_caption</td>"
   749                 .  "</tr>"
   750                 .  "<tr class='new_commands_header'>"
   751                 .  "<td width=100>Команда</td><td width=600>Описание</td>"
   752                 .  "</tr>"
   753                 .  $new_commands_section 
   754                 .  "</table>"
   755     }
   756     return $result;
   757 }
   759 #############
   760 # print_all
   761 #
   762 #
   763 #
   764 # In:       $_[0]       seconds_since_last_command
   765 # Out:                  "minutes passed" text
   767 sub minutes_passed
   768 {
   769         my $seconds_since_last_command = shift;
   770         my $result = "";
   771         if ($seconds_since_last_command > 7200) {
   772             my $hours_passed =  int($seconds_since_last_command/3600);
   773             my $passed_word  = $hours_passed % 10 == 1 ? "прошла"
   774                                                          : "прошло";
   775             my $hours_word   = $hours_passed % 10 == 1 ?   "часа":
   776                                                            "часов";
   777             $result .= "<div class='much_time_passed'>"
   778                     .  $passed_word." >".$hours_passed." ".$hours_word
   779                     .  "</div>\n";
   780         }
   781         elsif ($seconds_since_last_command > 600) {
   782             my $minutes_passed =  int($seconds_since_last_command/60);
   785             my $passed_word  = $minutes_passed % 100 > 10 
   786                             && $minutes_passed % 100 < 20 ? "прошло"
   787                              : $minutes_passed % 10 == 1  ? "прошла"
   788                                                           : "прошло";
   790             my $minutes_word = $minutes_passed % 100 > 10 
   791                             && $minutes_passed % 100 < 20 ? "минут" :
   792                                $minutes_passed % 10 == 1 ? "минута":
   793                                $minutes_passed % 10 == 0 ? "минут" :
   794                                $minutes_passed % 10  > 4 ? "минут" :
   795                                                            "минуты";
   797             if ($seconds_since_last_command < 1800) {
   798                 $result .= "<div class='time_passed'>"
   799                         .  $passed_word." ".$minutes_passed." ".$minutes_word
   800                         .  "</div>\n";
   801             }
   802             else {
   803                 $result .= "<div class='much_time_passed'>"
   804                         .  $passed_word." ".$minutes_passed." ".$minutes_word
   805                         .  "</div>\n";
   806             }
   807         }
   808         return $result;
   809 }
   811 #############
   812 # print_all
   813 #
   814 #
   815 #
   816 # In:       $_[0]       output_filename
   817 # Out:
   820 sub print_all
   821 {
   822     my $output_filename=$_[0];
   824     my $result;
   825     my ($command_lines,$toc)  = print_command_lines;
   826     my $files_section         = print_files;
   828     $result = print_header($toc);
   831 #    $result.= join " <br/>", keys %Sessions;
   832 #    for my $sess (keys %Sessions) {
   833 #            $result .= join " ", keys (%{$Sessions{$sess}});
   834 #            $result .= "<br/>";
   835 #    }
   837     $result.= "<h2 id='log'>Журнал</h2>"       . $command_lines;
   838     $result.= "<h2 id='files'>Файлы</h2>"      . $files_section if $files_section;
   839     $result.= "<h2 id='stat'>Статистика</h2>"  . print_stat;
   840     $result.= "<h2 id='help'>Справка</h2>"     . $Html_Help . "<br/>"; 
   841     $result.= "<h2 id='about'>О программе</h2>". $Html_About. "<br/>"; 
   842     $result.= print_footer;
   844     if ($output_filename eq "-") {
   845         print $result;
   846     }
   847     else {
   848         open(OUT, ">", $output_filename)
   849             or die "Can't open $output_filename for writing\n";
   850         print OUT $result;
   851         close(OUT);
   852     }
   853 }
   855 #############
   856 # print_header
   857 #
   858 #
   859 #
   860 # In:   $_[0]       Содержание
   861 # Out:              Распечатанный заголовок
   863 sub print_header
   864 {
   865     my $toc = $_[0];
   866     my $course_name = $Config{"course-name"};
   867     my $course_code = $Config{"course-code"};
   868     my $course_date = $Config{"course-date"};
   869     my $course_center = $Config{"course-center"};
   870     my $course_trainer = $Config{"course-trainer"};
   871     my $course_student = $Config{"course-student"};
   873     my $title    = "Журнал лабораторных работ";
   874     $title      .= " -- ".$course_student if $course_student;
   875     if ($course_date) {
   876         $title  .= " -- ".$course_date; 
   877         $title  .= $course_code ? "/".$course_code 
   878                                 : "";
   879     }
   880     else {
   881         $title  .= " -- ".$course_code if $course_code;
   882     }
   884     # Управляющая форма
   885     my $control_form .= "<div class='visibility_form' title='Выберите какие элементы должны быть показаны в журнале'>"
   886                      .  "<span class='header'>Видимые элементы</span>"
   887                      .  "<span class='window_controls'><a href='' onclick='' title='свернуть форму управления'>_</a> <a href='' onclick='' title='закрыть форму управления'>x</a></span>"
   888                      .  "<div><form>\n";
   889     for my $element (sort keys %Elements_Visibility)
   890     {
   891         my ($skip, @e) = split /\s+/, $element;
   892         my $showhide = join "", map { "ShowHide('$_');" } @e ;
   893         $control_form .= "<div><input type='checkbox' name='$e[0]' onclick=\"$showhide\" checked>".
   894                 $Elements_Visibility{$element}.
   895                 "</input></div>";
   896     }
   897     $control_form .= "</form>\n"
   898                   .  "</div>\n";
   900     my $result;
   901     $result = <<HEADER;
   902     <html>
   903     <head>
   904     <meta content='text/html; charset=utf-8' http-equiv='Content-Type' />
   905     <link rel='stylesheet' href='$Config{frontend_css}' type='text/css'/>
   906     <title>$title</title>
   907     </head>
   908     <body>
   909     <script>
   910     $Html_JavaScript
   911     </script>
   913 <!-- vvv Tigra Hints vvv -->
   914 <script language="JavaScript" src="/tigra/hints.js"></script>
   915 <script language="JavaScript" src="/tigra/hints_cfg.js"></script>
   916 <style>
   917 /* a class for all Tigra Hints boxes, TD object */
   918     .hintsClass
   919         {text-align: center; font-family: Verdana, Arial, Helvetica; padding: 0px 0px 0px 0px;}
   920 /* this class is used by Tigra Hints wrappers */
   921     .row
   922         {background: white;}
   923 </style>
   924 <!-- ^^^ Tigra Hints ^^^ -->
   927     <h1 onmouseover="myHint.show('1')" onmouseout="myHint.hide()">Журнал лабораторных работ</h1>
   928 HEADER
   929     if (    $course_student 
   930             || $course_trainer 
   931             || $course_name 
   932             || $course_code 
   933             || $course_date 
   934             || $course_center) {
   935             $result .= "<p>";
   936             $result .= "Выполнил $course_student<br/>"  if $course_student;
   937             $result .= "Проверил $course_trainer <br/>" if $course_trainer;
   938             $result .= "Курс "                          if $course_name 
   939                                                             || $course_code 
   940                                                             || $course_date;
   941             $result .= "$course_name "                  if $course_name;
   942             $result .= "($course_code)"                 if $course_code;
   943             $result .= ", $course_date<br/>"            if $course_date;
   944             $result .= "Учебный центр $course_center <br/>" if $course_center;
   945             $result .= "Фильтр ".join(" ", map("$filter{$_}=$_", keys %filter))."<br/>" if %filter;
   946             $result .= "</p>";
   947     }
   949     $result .= <<HEADER;
   950     <table width='100%'>
   951     <tr>
   952     <td width='*'>
   954     <table border=0 id='toc' class='toc'>
   955     <tr>
   956     <td>
   957     <div class='toc_title'>Содержание</div>
   958     <ul>
   959         <li><a href='#log'>Журнал</a></li>
   960         <ul>$toc</ul>
   961         <li><a href='#files'>Файлы</a></li>
   962         <li><a href='#stat'>Статистика</a></li>
   963         <li><a href='#help'>Справка</a></li>
   964         <li><a href='#about'>О программе</a></li>
   965     </ul>
   966     </td>
   967     </tr>
   968     </table>
   970     </td>
   971     <td valign='top' width=200>$control_form</td>
   972     </tr>
   973     </table>
   974 HEADER
   976     return $result;
   977 }
   980 #############
   981 # print_footer
   982 #
   983 #
   984 #
   985 #
   986 #
   988 sub print_footer
   989 {
   990     return "</body>\n</html>\n";
   991 }
   996 #############
   997 # print_stat
   998 #
   999 #
  1000 #
  1001 # In:
  1002 # Out:
  1004 sub print_stat
  1005 {
  1006     %StatNames = (
  1007         FirstCommand        => "Время первой команды журнала",
  1008         LastCommand         => "Время последней команды журнала",
  1009         TotalCommands       => "Количество командных строк в журнале",
  1010         ErrorsPercentage    => "Процент команд с ненулевым кодом завершения, %",
  1011         MistypesPercentage  => "Процент синтаксически неверно набранных команд, %",
  1012         TotalTime           => "Суммарное время работы с терминалом <sup><font size='-2'>*</font></sup>, час",
  1013         CommandsPerTime     => "Количество командных строк в единицу времени, команда/мин",
  1014         CommandsFrequency   => "Частота использования команд",
  1015         RareCommands        => "Частота использования этих команд < 0.5%",
  1016     );
  1017     @StatOrder = (
  1018         FirstCommand,
  1019         LastCommand,
  1020         TotalCommands,
  1021         ErrorsPercentage,
  1022         MistypesPercentage,
  1023         TotalTime,
  1024         CommandsPerTime,
  1025         CommandsFrequency,
  1026         RareCommands,
  1027     );
  1029     # Подготовка статистики к выводу
  1030     # Некоторые значения пересчитываются!
  1031     # Дальше их лучше уже не использовать!!!
  1033     my %CommandsFrequency = %frequency_of_command;
  1035     $Stat{TotalTime} ||= 0;
  1036     my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($Stat{FirstCommand} || 0);
  1037     $Stat{FirstCommand} = sprintf "%02i:%02i:%02i %04i-%2i-%2i", $hour, $min, $sec,  $year+1900, $mon+1, $mday;
  1038     ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($Stat{LastCommand} || 0);
  1039     $Stat{LastCommand} = sprintf "%02i:%02i:%02i %04i-%2i-%2i", $hour, $min, $sec,  $year+1900, $mon+1, $mday;
  1040     if ($Stat{TotalCommands}) {
  1041         $Stat{ErrorsPercentage} = sprintf "%5.2f", $Stat{ErrorCommands}*100/$Stat{TotalCommands};
  1042         $Stat{MistypesPercentage} = sprintf "%5.2f", $Stat{MistypedCommands}*100/$Stat{TotalCommands};
  1043     }
  1044     $Stat{CommandsPerTime} = sprintf "%5.2f", $Stat{TotalCommands}*60/$Stat{TotalTime}
  1045         if $Stat{TotalTime};
  1046     $Stat{TotalTime} = sprintf "%5.2f", $Stat{TotalTime}/60/60;
  1048     my $total_commands=0;
  1049     for $command (keys %CommandsFrequency){
  1050         $total_commands += $CommandsFrequency{$command};
  1051     }
  1052     if ($total_commands) {
  1053         for $command (reverse sort {$CommandsFrequency{$a} <=> $CommandsFrequency{$b}} keys %CommandsFrequency){
  1054             my $command_html;
  1055             my $percentage = sprintf "%5.2f",$CommandsFrequency{$command}*100/$total_commands;
  1056             if ($percentage < 0.5) {
  1057                 my $hint = make_comment($command);
  1058                 $command_html = "$command";
  1059                 $command_html = "<span title='$hint' class='with_hint'>$command_html</span>" if $hint;
  1060                 $command_html = "<span class='without_hint'>$command_html</span>" if not $hint;
  1061                 my $command_html = "<tt>$command_html</tt>";
  1062                 $Stat{RareCommands} .= $command_html."<sub><font size='-2'>".$CommandsFrequency{$command}."</font></sub> , ";
  1063             }
  1064             else {
  1065                 my $hint = make_comment($command);
  1066                 $command_html = "$command";
  1067                 $command_html = "<span title='$hint' class='with_hint'>$command_html</span>" if $hint;
  1068                 $command_html = "<span class='without_hint'>$command_html</span>" if not $hint;
  1069                 my $command_html = "<tt>$command_html</tt>";
  1070                 $percentage = sprintf "%5.2f",$percentage;
  1071                 $Stat{CommandsFrequency} .= "<tr><td>".$command_html."</td><td>".$CommandsFrequency{$command}."</td>".
  1072                     "<td>|".("="x int($CommandsFrequency{$command}*100/$total_commands))."| $percentage%</td></tr>";
  1073             }
  1074         }
  1075         $Stat{CommandsFrequency} = "<table>".$Stat{CommandsFrequency}."</table>";
  1076         $Stat{RareCommands} =~ s/, $// if $Stat{RareCommands};
  1077     }
  1079     my $result = q();
  1080     for my $stat (@StatOrder) {
  1081         next unless $Stat{"$stat"};
  1082         $result .= "<tr valign='top'><td width='300'>".$StatNames{"$stat"}."</td><td>".$Stat{"$stat"}."</td></tr>"
  1083     }
  1084     $result  = "<table>$result</table>"
  1085              . "<font size='-2'>____<br/>*) Интервалы неактивности длительностью "
  1086              .  ($Config{stat_inactivity_interval}/60)
  1087              . " минут и более не учитываются</font></br>";
  1089     return $result;
  1090 }
  1093 sub collapse_list($)
  1094 {
  1095     my $res = "";
  1096     for my $elem (@{$_[0]}) {
  1097         if (ref $elem eq "ARRAY") {
  1098             $res .= "<ul>".collapse_list($elem)."</ul>";
  1099         }
  1100         else
  1101         {
  1102             $res .= "<li>".$elem."</li>";
  1103         }
  1104     }
  1105     return $res;
  1106 }
  1109 sub print_files
  1110 {
  1111     my $result = qq(); 
  1112     my @toc;
  1113     for my $file (sort keys %Files) {
  1114           my $div_id = "file:$file";
  1115           $div_id =~ s@/@_@g;
  1116           push @toc, "<a href='#$div_id'>$file</a>";
  1117           $result .= "<div class='filename' id='$div_id'>".$file."</div>\n"
  1118                   .  "<div class='file_navigation'><a href='#command:".$Files{$file}->{source_command_id}."'>".">"."</a></div>"
  1119                   .  "<div class='filedata'><pre>".$Files{$file}->{content}."</pre></div>";
  1120     }
  1121     return "<div class='files_toc'>".collapse_list(\@toc)."</div>".$result;
  1122 }
  1125 sub init_variables
  1126 {
  1127 $Html_Help = <<HELP;
  1128     Для того чтобы использовать LiLaLo, не нужно знать ничего особенного:
  1129     всё происходит само собой.
  1130     Однако, чтобы ведение и последующее использование журналов
  1131     было как можно более эффективным, желательно иметь в виду следующее:
  1132     <ol>
  1133     <li><p> 
  1134     В журнал автоматически попадают все команды, данные в любом терминале системы.
  1135     </p></li>
  1136     <li><p>
  1137     Для того чтобы убедиться, что журнал на текущем терминале ведётся, 
  1138     и команды записываются, дайте команду w.
  1139     В поле WHAT, соответствующем текущему терминалу, 
  1140     должна быть указана программа script.
  1141     </p></li>
  1142     <li><p>
  1143     Команды, при наборе которых были допущены синтаксические ошибки, 
  1144     выводятся перечёркнутым текстом:
  1145 <table>
  1146 <tr class='command'>
  1147 <td class='script'>
  1148 <pre class='_mistyped_cline'>
  1149 \$ l s-l</pre>
  1150 <pre class='_mistyped_output'>bash: l: command not found
  1151 </pre>
  1152 </td>
  1153 </tr>
  1154 </table>
  1155 <br/>
  1156     </p></li>
  1157     <li><p>
  1158     Если код завершения команды равен нулю, 
  1159     команда была выполнена без ошибок.
  1160     Команды, код завершения которых отличен от нуля, выделяются цветом.
  1161 <table>
  1162 <tr class='command'>
  1163 <td class='script'>
  1164 <pre class='_wrong_cline'>
  1165 \$ test 5 -lt 4</pre>
  1166 </pre>
  1167 </td>
  1168 </tr>
  1169 </table>
  1170     Обратите внимание на то, что код завершения команды может быть отличен от нуля
  1171     не только в тех случаях, когда команда была выполнена с ошибкой.
  1172     Многие команды используют код завершения, например, для того чтобы показать результаты проверки
  1173 <br/>
  1174     </p></li>
  1175     <li><p>
  1176     Команды, ход выполнения которых был прерван пользователем, выделяются цветом.
  1177 <table>
  1178 <tr class='command'>
  1179 <td class='script'>
  1180 <pre class='_interrupted_cline'>
  1181 \$ find / -name abc</pre>
  1182 <pre class='interrupted_output'>find: /home/devi-orig/.gnome2: Keine Berechtigung
  1183 find: /home/devi-orig/.gnome2_private: Keine Berechtigung
  1184 find: /home/devi-orig/.nautilus/metafiles: Keine Berechtigung
  1185 find: /home/devi-orig/.metacity: Keine Berechtigung
  1186 find: /home/devi-orig/.inkscape: Keine Berechtigung
  1187 ^C
  1188 </pre>
  1189 </td>
  1190 </tr>
  1191 </table>
  1192 <br/>
  1193     </p></li>
  1194     <li><p>
  1195     Команды, выполненные с привилегиями суперпользователя,
  1196     выделяются слева красной чертой.
  1197 <table>
  1198 <tr class='command'>
  1199 <td class='script'>
  1200 <pre class='_root_cline'>
  1201 # id</pre>
  1202 <pre class='_root_output'>
  1203 uid=0(root) gid=0(root) Gruppen=0(root)
  1204 </pre>
  1205 </td>
  1206 </tr>
  1207 </table>
  1208     <br/>
  1209     </p></li>
  1210     <li><p>
  1211     Изменения, внесённые в текстовый файл с помощью редактора, 
  1212     запоминаются и показываются в журнале в формате ed.
  1213     Строки, начинающиеся символом "<", удалены, а строки,
  1214     начинающиеся символом ">" -- добавлены.
  1215 <table>
  1216 <tr class='command'>
  1217 <td class='script'>
  1218 <pre class='cline'>
  1219 \$ vi ~/.bashrc</pre>
  1220 <table><tr><td width='5'/><td class='diff'><pre>2a3,5
  1221 >    if [ -f /usr/local/etc/bash_completion ]; then
  1222 >         . /usr/local/etc/bash_completion
  1223 >        fi
  1224 </pre></td></tr></table></td>
  1225 </tr>
  1226 </table>
  1227     <br/>
  1228     </p></li>
  1229     <li><p>
  1230     Для того чтобы изменить файл в соответствии с показанными в диффшоте
  1231     изменениями, можно воспользоваться командой patch.
  1232     Нужно скопировать изменения, запустить программу patch, указав в
  1233     качестве её аргумента файл, к которому применяются изменения,
  1234     и всавить скопированный текст:
  1235 <table>
  1236 <tr class='command'>
  1237 <td class='script'>
  1238 <pre class='cline'>
  1239 \$ patch ~/.bashrc</pre>
  1240 </td>
  1241 </tr>
  1242 </table>
  1243     В данном случае изменения применяются к файлу ~/.bashrc
  1244     </p></li>
  1245     <li><p>
  1246     Для того чтобы получить краткую справочную информацию о команде, 
  1247     нужно подвести к ней мышь. Во всплывающей подсказке появится краткое
  1248     описание команды.
  1249     </p>
  1250     <p>
  1251     Если справочная информация о команде есть, 
  1252     команда выделяется голубым фоном, например: <span class="with_hint" title="главный текстовый редактор Unix">vi</span>.
  1253     Если справочная информация отсутствует,
  1254     команда выделяется розовым фоном, например: <span class="without_hint">notepad.exe</span>.
  1255     Справочная информация может отсутствовать в том случае, 
  1256     если (1) команда введена неверно; (2) если распознавание команды LiLaLo выполнено неверно;
  1257     (3) если информация о команде неизвестна LiLaLo.
  1258     Последнее возможно для редких команд.
  1259     </p></li>
  1260     <li><p>
  1261     Большие, в особенности многострочные, всплывающие подсказки лучше 
  1262     всего показываются браузерами KDE Konqueror, Apple Safari и Microsoft Internet Explorer.
  1263     В браузерах Mozilla и Firefox они отображаются не полностью, 
  1264     а вместо перевода строки выводится специальный символ.
  1265     </p></li>
  1266     <li><p>
  1267     Время ввода команды, показанное в журнале, соответствует времени 
  1268     <i>начала ввода командной строки</i>, которое равно тому моменту, 
  1269     когда на терминале появилось приглашение интерпретатора
  1270     </p></li>
  1271     <li><p>
  1272     Имя терминала, на котором была введена команда, показано в специальном блоке.
  1273     Этот блок показывается только в том случае, если терминал
  1274     текущей команды отличается от терминала предыдущей.
  1275     </p></li>
  1276     <li><p>
  1277     Вывод не интересующих вас в настоящий момент элементов журнала,
  1278     таких как время, имя терминала и других, можно отключить.
  1279     Для этого нужно воспользоваться <a href='#visibility_form'>формой управления журналом</a>
  1280     вверху страницы.
  1281     </p></li>
  1282     <li><p>
  1283     Небольшие комментарии к командам можно вставлять прямо из командной строки.
  1284     Комментарий вводится прямо в командную строку, после символов #^ или #v.
  1285     Символы ^ и v показывают направление выбора команды, к которой относится комментарий:
  1286     ^ - к предыдущей, v - к следующей.
  1287     Например, если в командной строке было введено:
  1288 <pre class='cline'>
  1289 \$ whoami
  1290 </pre>
  1291 <pre class='output'>
  1292 user
  1293 </pre>
  1294 <pre class='cline'>
  1295 \$ #^ Интересно, кто я?
  1296 </pre>
  1297     в журнале это будет выглядеть так:
  1299 <pre class='cline'>
  1300 \$ whoami
  1301 </pre>
  1302 <pre class='output'>
  1303 user
  1304 </pre>
  1305 <table class='note'><tr><td width='100%' class='note_text'>
  1306 <tr> <td> Интересно, кто я?<br/> </td></tr></table> 
  1307     </p></li>
  1308     <li><p>
  1309     Если комментарий содержит несколько строк,
  1310     его можно вставить в журнал следующим образом:
  1311 <pre class='cline'>
  1312 \$ whoami
  1313 </pre>
  1314 <pre class='output'>
  1315 user
  1316 </pre>
  1317 <pre class='cline'>
  1318 \$ cat > /dev/null #^ Интересно, кто я?
  1319 </pre>
  1320 <pre class='output'>
  1321 Программа whoami выводит имя пользователя, под которым 
  1322 мы зарегистрировались в системе.
  1323 -
  1324 Она не может ответить на вопрос о нашем назначении 
  1325 в этом мире.
  1326 </pre>
  1327     В журнале это будет выглядеть так:
  1328 <table>
  1329 <tr class='command'>
  1330 <td class='script'>
  1331 <pre class='cline'>
  1332 \$ whoami</pre>
  1333 <pre class='output'>user
  1334 </pre>
  1335 <table class='note'><tr><td class='note_title'>Интересно, кто я?</td></tr><tr><td width='100%' class='note_text'>
  1336 Программа whoami выводит имя пользователя, под которым<br/>
  1337 мы зарегистрировались в системе.<br/>
  1338 <br/>
  1339 Она не может ответить на вопрос о нашем назначении<br/>
  1340 в этом мире.<br/>
  1341 </td></tr></table>
  1342 </td>
  1343 </tr>
  1344 </table>
  1345     Для разделения нескольких абзацев между собой
  1346     используйте символ "-", один в строке.
  1347     <br/>
  1348 </p></li>
  1349     <li><p>
  1350     Комментарии, не относящиеся непосредственно ни к какой из команд, 
  1351     добавляются точно таким же способом, только вместо симолов #^ или #v 
  1352     нужно использовать символы #=
  1353     </p></li>
  1355     <p><li>
  1356     Содержимое файла может быть показано в журнале.
  1357     Для этого его нужно вывести с помощью программы cat.
  1358     Если вывод команды отметить симоволами #!, 
  1359     содержимое файла будет показано в журнале
  1360     в специально отведённой для этого секции.
  1361     </li></p>
  1363     <p>
  1364     <li>
  1365     Для того чтобы вставить скриншот интересующего вас окна в журнал,
  1366     нужно воспользоваться командой l3shot.
  1367     После того как команда вызвана, нужно с помощью мыши выбрать окно, которое
  1368     должно быть в журнале.
  1369     </li>
  1370     </p>
  1372     <p>
  1373     <li>
  1374     Команды в журнале расположены в хронологическом порядке.
  1375     Если две команды давались одна за другой, но на разных терминалах,
  1376     в журнале они будут рядом, даже если они не имеют друг к другу никакого отношения.
  1377 <pre>
  1378 1
  1379     2
  1380 3   
  1381     4
  1382 </pre>
  1383     Группы команд, выполненных на разных терминалах, разделяются специальной линией.
  1384     Под этой линией в правом углу показано имя терминала, на котором выполнялись команды.
  1385     Для того чтобы посмотреть команды только одного сенса, 
  1386     нужно щёкнуть по этому названию.
  1387     </li>
  1388     </p>
  1389 </ol>
  1390 HELP
  1392 $Html_About = <<ABOUT;
  1393     <p>
  1394     LiLaLo (L3) расшифровывается как Live Lab Log.<br/>
  1395     Программа разработана для повышения эффективности обучения Unix/Linux-системам.<br/>
  1396     (c) Игорь Чубин, 2004-2006<br/>
  1397     </p>
  1398 ABOUT
  1399 $Html_About.='$Id$ </p>';
  1401 $Html_JavaScript = <<JS;
  1402     function getElementsByClassName(Class_Name)
  1403     {
  1404         var Result=new Array();
  1405         var All_Elements=document.all || document.getElementsByTagName('*');
  1406         for (i=0; i<All_Elements.length; i++)
  1407             if (All_Elements[i].className==Class_Name)
  1408         Result.push(All_Elements[i]);
  1409         return Result;
  1410     }
  1411     function ShowHide (name)
  1412     {
  1413         elements=getElementsByClassName(name);
  1414         for(i=0; i<elements.length; i++)
  1415             if (elements[i].style.display == "none")
  1416                 elements[i].style.display = "";
  1417             else
  1418                 elements[i].style.display = "none";
  1419             //if (elements[i].style.visibility == "hidden")
  1420             //  elements[i].style.visibility = "visible";
  1421             //else
  1422             //  elements[i].style.visibility = "hidden";
  1423     }
  1424     function filter_by_output(text)
  1425     {
  1427         var jjj=0;
  1429         elements=getElementsByClassName('command');
  1430         for(i=0; i<elements.length; i++) {
  1431             subelems = elements[i].getElementsByTagName('pre');
  1432             for(j=0; j<subelems.length; j++) {
  1433                 if (subelems[j].className = 'output') {
  1434                     var str = new String(subelems[j].nodeValue);
  1435                     if (jjj != 1) { 
  1436                         alert(str);
  1437                         jjj=1;
  1438                     }
  1439                     if (str.indexOf(text) >0) 
  1440                         subelems[j].style.display = "none";
  1441                     else
  1442                         subelems[j].style.display = "";
  1444                 }
  1446             }
  1447         }       
  1449     }
  1450 JS
  1452 %Search_Machines = (
  1453         "google" =>     {   "query" =>  "http://www.google.com/search?q=" ,
  1454                     "icon"  =>  "$Config{frontend_google_ico}" },
  1455         "freebsd" =>    {   "query" =>  "http://www.freebsd.org/cgi/man.cgi?query=",
  1456                     "icon"  =>  "$Config{frontend_freebsd_ico}" },
  1457         "linux"  =>     {   "query" =>  "http://man.he.net/?topic=",
  1458                     "icon"  =>  "$Config{frontend_linux_ico}"},
  1459         "opennet"  =>   {   "query" =>  "http://www.opennet.ru/search.shtml?words=",
  1460                     "icon"  =>  "$Config{frontend_opennet_ico}"},
  1461         "local" =>  {   "query" =>  "http://www.freebsd.org/cgi/man.cgi?query=",
  1462                     "icon"  =>  "$Config{frontend_local_ico}" },
  1464     );
  1466 %Elements_Visibility = (
  1467         "0 new_commands_table"      =>  "новые команды",
  1468         "1 diff"      =>  "редактор",
  1469         "2 time"      =>  "время",
  1470         "3 ttychange"     =>  "терминал",
  1471         "4 wrong_output wrong_cline wrong_root_output wrong_root_cline" 
  1472                 =>  "команды с ненулевым кодом завершения",
  1473         "5 mistyped_output mistyped_cline mistyped_root_output mistyped_root_cline" 
  1474                 =>  "неверно набранные команды",
  1475         "6 interrupted_output interrupted_cline interrupted_root_output interrupted_root_cline" 
  1476                 =>  "прерванные команды",
  1477         "7 tab_completion_output tab_completion_cline"    
  1478                 =>  "продолжение с помощью tab"
  1479 );
  1481 @Day_Name      = qw/ Воскресенье Понедельник Вторник Среда Четверг Пятница Суббота /;
  1482 @Month_Name    = qw/ Январь Февраль Март Апрель Май Июнь Июль Август Сентябрь Октябрь Ноябрь Декабрь /;
  1483 @Of_Month_Name = qw/ Января Февраля Марта Апреля Мая Июня Июля Августа Сентября Октября Ноября Декабря /;
  1484 }
  1489 # Временно удалённый код
  1490 # Возможно, он не понадобится уже никогда
  1493 sub search_by
  1494 {
  1495     my $sm = shift;
  1496     my $topic = shift;
  1497     $topic =~ s/ /+/;
  1499     return "<a href='". $Search_Machines{$sm}->{"query"}."$topic'><img width='16' height='16' src='".
  1500                 $Search_Machines{$sm}->{"icon"}."' border='0'/></a>";
  1501 }
