lilalo
view l3-frontend @ 74:a10db759e587
Перешёл на новый формат приглашения.
Ура Ура Ура!
Теперь в нём есть информация
о номере строки в истории (history),
текущем каталоге (pwd),
времени появления приглашения (time)
Давно пора было!
Ура Ура Ура!
Теперь в нём есть информация
о номере строки в истории (history),
текущем каталоге (pwd),
времени появления приглашения (time)
Давно пора было!
| author | devi | 
|---|---|
| date | Thu Feb 09 18:47:04 2006 +0200 (2006-02-09) | 
| parents | 1e1422588716 | 
| children | 58ea78973bbb | 
 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 our %Files;
    17 # vvv Инициализация переменных выполняется процедурой init_variables
    18 our @Day_Name;
    19 our @Month_Name;
    20 our @Of_Month_Name;
    21 our %Search_Machines;
    22 our %Elements_Visibility;
    23 # ^^^
    25 our %Stat;
    26 our %CommandsFDistribution; # Сколько раз в журнале встречается какая команда
    27 our $table_number=1;
    29 my %mywi_cache_for;         # Кэш для экономии обращений к mywi
    31 sub make_comment;
    32 sub make_new_entries_table;
    33 sub load_command_lines_from_xml;
    34 sub load_sessions_from_xml;
    35 sub sort_command_lines;
    36 sub process_command_lines;
    37 sub init_variables;
    38 sub main;
    39 sub collapse_list($);
    41 sub print_all;
    42 sub print_command_lines;
    43 sub print_files;
    44 sub print_stat;
    45 sub print_header;
    46 sub print_footer;
    48 main();
    50 sub main
    51 {
    52     $| = 1;
    54     init_variables();
    55     init_config();
    56     $Config{frontend_ico_path}=$Config{frontend_css};
    57     $Config{frontend_ico_path}=~s@/[^/]*$@@;
    59     open_mywi_socket();
    60     load_command_lines_from_xml($Config{"backend_datafile"});
    61     load_sessions_from_xml($Config{"backend_datafile"});
    62     sort_command_lines;
    63     process_command_lines;
    64     print_all($Config{"output"});
    65     close_mywi_socket;
    66 }
    68 # extract_from_cline
    70 # In:   $what       = commands | args
    71 # Out:  return      ссылка на хэш, содержащий результаты разбора
    72 #                   команда => позиция
    74 # Разобрать командную строку $_[1] и возвратить хэш, содержащий 
    75 # номер первого появление команды в строке:
    76 #   команда => первая позиция
    77 sub extract_from_cline
    78 {
    79     my $what = $_[0];
    80     my $cline = $_[1];
    81     my @lists = split /\;/, $cline;
    84     my @command_lines = ();
    85     for my $command_list (@lists) {
    86         push(@command_lines, split(/\|/, $command_list));
    87     }
    89     my %position_of_command;
    90     my %position_of_arg;
    91     my $i=0;
    92     for my $command_line (@command_lines) {
    93         $command_line =~ s@^\s*@@;
    94         $command_line =~ /\s*(\S+)\s*(.*)/;
    95         if ($1 && $1 eq "sudo" ) {
    96             $position_of_command{"$1"}=$i++;
    97             $command_line =~ s/\s*sudo\s+//;
    98         }
    99         if ($command_line !~ m@^\s*\S*/etc/@) {
   100             $command_line =~ s@^\s*\S+/@@;
   101         }
   103         $command_line =~ /\s*(\S+)\s*(.*)/;
   104         my $command = $1;
   105         my $args = $2;
   106         if ($command && !defined $position_of_command{"$command"}) {
   107                 $position_of_command{"$command"}=$i++;
   108         };  
   109         if ($args) {
   110             my @args = split (/\s+/, $args);
   111             for my $a (@args) {
   112                 $position_of_arg{"$a"}=$i++
   113                     if !defined $position_of_arg{"$a"};
   114             };  
   115         }
   116     }
   118     if ($what eq "commands") {
   119         return \%position_of_command;
   120     } else {
   121         return \%position_of_arg;
   122     }
   124 }
   129 #
   130 # Подпрограммы для работы с mywi
   131 #
   133 sub open_mywi_socket
   134 {
   135     $Mywi_Socket = IO::Socket::INET->new(
   136                 PeerAddr => $Config{mywi_server},
   137                 PeerPort => $Config{mywi_port},
   138                 Proto    => "tcp",
   139                 Type     => SOCK_STREAM);
   140 }
   142 sub close_mywi_socket
   143 {
   144     close ($Mywi_Socket) if $Mywi_Socket ;
   145 }
   148 sub mywi_client
   149 {
   150     my $query = $_[0];
   151     my $mywi;
   153     open_mywi_socket;
   154     if ($Mywi_Socket) {
   155         local $| = 1;
   156         local $/ = "";
   157         print $Mywi_Socket $query."\n";
   158         $mywi = <$Mywi_Socket>;
   159         $mywi = "" if $mywi =~ /nothing app/;
   160     }
   161     close_mywi_socket;
   162     return $mywi;
   163 }
   165 sub make_comment
   166 {
   167     my $cline = $_[0];
   168     #my $files = $_[1];
   170     my @comments;
   171     my @commands = keys %{extract_from_cline("commands", $cline)};
   172     my @args = keys %{extract_from_cline("args", $cline)};
   173     return if (!@commands && !@args);
   174     #return "commands=".join(" ",@commands)."; files=".join(" ",@files);
   176     # Commands
   177     for my $command (@commands) {
   178         $command =~ s/'//g;
   179         $CommandsFDistribution{$command}++;
   180         if (!$Commands_Description{$command}) {
   181             $mywi_cache_for{$command} ||= mywi_client ($command) || "";
   182             my $mywi = join ("\n", grep(/\([18]|sh|script\)/, split(/\n/, $mywi_cache_for{$command})));
   183             $mywi =~ s/\s+/ /;
   184             if ($mywi !~ /^\s*$/) {
   185                 $Commands_Description{$command} = $mywi;
   186             }
   187             else {
   188                 next;
   189             }
   190         }
   192         push @comments, $Commands_Description{$command};
   193     }
   194     return join("
\n", @comments);
   196     # Files
   197     for my $arg (@args) {
   198         $arg =~ s/'//g;
   199         if (!$Args_Description{$arg}) {
   200             my $mywi;
   201             $mywi = mywi_client ($arg);
   202             $mywi = join ("\n", grep(/\([5]\)/, split(/\n/, $mywi)));
   203             $mywi =~ s/\s+/ /;
   204             if ($mywi !~ /^\s*$/) {
   205                 $Args_Description{$arg} = $mywi;
   206             }
   207             else {
   208                 next;
   209             }
   210         }
   212         push @comments, $Args_Description{$arg};
   213     }
   215 }
   217 =cut
   218 Процедура load_command_lines_from_xml выполняет загрузку разобранного lab-скрипта
   219 из XML-документа в переменную @Command_Lines
   221 # In:       $datafile           имя файла
   222 # Out:      @CommandLines       загруженные командные строки
   224 Предупреждение!
   225 Процедура не в состоянии обрабатывать XML-документ любой структуры.
   226 В действительности файл cache из которого загружаются данные 
   227 просто напоминает XML с виду.
   228 =cut
   229 sub load_command_lines_from_xml
   230 {
   231     my $datafile = $_[0];
   233     open (CLASS, $datafile)
   234         or die "Can't open file of the class ",$datafile,"\n";
   235     local $/;
   236     $data = <CLASS>;
   237     close(CLASS);
   239     for $command ($data =~ m@<command>(.*?)</command>@sg) {
   240         my %cl;
   241         while ($command =~ m@<([^>]*?)>(.*?)</\1>@sg) {
   242             $cl{$1} = $2;
   243         }
   244         push @Command_Lines, \%cl;
   245     }
   246 }
   248 sub load_sessions_from_xml
   249 {
   250     my $datafile = $_[0];
   252     open (CLASS, $datafile)
   253         or die "Can't open file of the class ",$datafile,"\n";
   254     local $/;
   255     my $data = <CLASS>;
   256     close(CLASS);
   258     for my $session ($data =~ m@<session>(.*?)</session>@sg) {
   259         my %session;
   260         while ($session =~ m@<([^>]*?)>(.*?)</\1>@sg) {
   261             $session{$1} = $2;
   262         }
   263         $Sessions{$session{local_session_id}} = \%session;
   264     }
   265 }
   268 # sort_command_lines
   269 # In:   @Command_Lines
   270 # Out:  @Command_Lies_Index
   272 sub sort_command_lines
   273 {
   275     my @index;
   276     for (my $i=0;$i<=$#Command_Lines;$i++) {
   277         $index[$i]=$i;
   278     }
   280     @Command_Lines_Index = sort {
   281         $Command_Lines[$index[$a]]->{"time"} <=> $Command_Lines[$index[$b]]->{"time"}
   282     } @index;
   284 }
   286 ##################
   287 # process_command_lines
   288 #
   289 # Обрабатываются командные строки @Command_Lines
   290 # Для каждой строки определяется:
   291 #   class   класс    
   292 #   note    комментарий 
   293 #
   294 # In:        @Command_Lines_Index
   295 # In-Out:    @Command_Lines
   297 sub process_command_lines
   298 {
   299     for my $i (@Command_Lines_Index) {
   300         my $cl = \$Command_Lines[$i];
   302         next if !$cl;
   304         $$cl->{id} = $$cl->{"time"};
   306         $$cl->{err} ||=0;
   308         # Класс команды
   310         $$cl->{"class"} =   $$cl->{"err"} eq 130 ?  "interrupted"
   311                         :   $$cl->{"err"} eq 127 ?  "mistyped"
   312                         :   $$cl->{"err"}        ?  "wrong"
   313                         :                           "normal";
   315         if ($$cl->{"cline"} && 
   316             $$cl->{"cline"} =~ /[^|`]\s*sudo/
   317             || $$cl->{"uid"} eq 0) {
   318             $$cl->{"class"}.="_root";
   319         }
   322 #Обработка пометок
   323 #  Если несколько пометок (notes) идут подряд, 
   324 #  они все объединяются
   326         if ($$cl->{cline}=~ m@cat[^#]*#([\^=v])\s*(.*)@) {
   328             my $note_operator = $1;
   329             my $note_title = $2;
   331             if ($note_operator eq "=") {
   332                 $$cl->{"class"} = "note";
   333                 $$cl->{"note"} = $$cl->{"output"};
   334                 $$cl->{"note_title"} = $2;
   335             }
   336             else {
   337                 my $j = $i;
   338                 if ($note_operator eq "^") {
   339                     $j--;
   340                     $j-- while ($j >=0  && (!$Command_Lines[$j] || $Command_Lines[$j]->{tty} ne $$cl->{tty}));
   341                 }
   342                 elsif ($note_operator eq "v") {
   343                     $j++;
   344                     $j++ while ($j <= @Command_Lines  && (!$Command_Lines[$j] || $Command_Lines[$j]->{tty} ne $$cl->{tty}));
   345                 }
   346                 $Command_Lines[$j]->{note_title}=$note_title;
   347                 $Command_Lines[$j]->{note}.=$$cl->{output};
   348                 $$cl=0;
   349             }
   350         }
   351         elsif ($$cl->{cline}=~ /#([\^=v])(.*)/) {
   353             my $note_operator = $1;
   354             my $note_text = $2;
   356             if ($note_operator eq "=") {
   357                 $$cl->{"class"} = "note";
   358                 $$cl->{"note"} = $note_text;
   359             }
   360             else {
   361                 my $j=$i;
   362                 if ($note_operator eq "^") {
   363                     $j--;
   364                     $j-- while ($j >=0  && (!$Command_Lines[$j] || $Command_Lines[$j]->{tty} ne $$cl->{tty}));
   365                 }
   366                 elsif ($note_operator eq "v") {
   367                     $j++;
   368                     $j++ while ($j <= @Command_Lines  && $Command_Lines[$j]->{tty} ne $$cl->{tty} || !$Command_Lines[$j]);
   369                 }
   370                 $Command_Lines[$j]->{note}.="$note_text\n";
   371                 $$cl=0;
   372             }
   373         }
   374     }   
   376 }
   379 =cut
   380 Процедура print_command_lines выводит HTML-представление
   381 разобранного lab-скрипта. 
   383 Разобранный lab-скрипт должен находиться в массиве @Command_Lines
   384 =cut
   386 sub print_command_lines
   387 {
   389     my @toc;                # Оглавление
   390     my $note_number=0;
   392     my $result = q();
   393     my $this_day_resut = q();
   395     my $cl;
   396     my $last_tty="";
   397     my $last_day=q();
   398     my $last_wday=q();
   399     my $in_range=0;
   401     my $current_command=0;
   403     my @known_commands;
   405     my %filter;
   407     if ($Config{filter}) {
   408         # Инициализация фильтра
   409         for (split /&/,$Config{filter}) {
   410             my ($var, $val) = split /=/;
   411             $filter{$var} = $val || "";
   412         }
   413     }
   415     #$result = "Filter=".$Config{filter}."\n";
   417     $Stat{LastCommand}   ||= 0;
   418     $Stat{TotalCommands} ||= 0;
   419     $Stat{ErrorCommands} ||= 0;
   420     $Stat{MistypedCommands} ||= 0;
   422     my %new_entries_of = (
   423         "1 1"     =>   "программы пользователя",
   424         "2 8"     =>   "программы администратора",
   425         "3 sh"    =>   "команды интерпретатора",
   426         "4 script"=>   "скрипты",
   427     );
   429 COMMAND_LINE:
   430     for my $k (@Command_Lines_Index) {
   432         my $cl=$Command_Lines[$Command_Lines_Index[$current_command++]];
   433         next unless $cl;
   435 # Пропускаем команды, с одинаковым временем
   436 # Это не совсем правильно.
   437 # Возможно, что это команды, набираемые с помощью <completion>
   438 # или запомненные с помощью <ctrl-c>
   440         next if $Stat{LastCommand} == $cl->{time};
   442 # Пропускаем строки, которые противоречат фильтру
   443 # Если у нас недостаточно информации о том, подходит строка под  фильтр или нет, 
   444 # мы её выводим
   446         #$result .= "before<br/>";
   447         for my $filter_key (keys %filter) {
   448             #$result .= "undefined local session id<br/>\n" if !defined($cl->{local_session_id});
   449             #$result .= "undefined filter key $filter_key <br/>\n" if !defined($Sessions{$cl->{local_session_id}}->{$filter_key});
   450             #$result .= $Sessions{$cl->{local_session_id}}->{$filter_key}." != ".$filter{$filter_key};
   451             next COMMAND_LINE if 
   452                 defined($cl->{local_session_id}) 
   453                 && defined($Sessions{$cl->{local_session_id}}->{$filter_key}) 
   454                 && $Sessions{$cl->{local_session_id}}->{$filter_key} ne $filter{$filter_key};
   455         }
   457 # Набираем статистику
   458 # Хэш %Stat
   460         $Stat{FirstCommand} = $cl->{time} unless $Stat{FirstCommand};
   461         if ($cl->{time} - $Stat{LastCommand} < $Config{stat_inactivity_interval}) {
   462             $Stat{TotalTime} += $cl->{time} - $Stat{LastCommand}
   463         }
   464         my $seconds_since_last_command = $cl->{time} - $Stat{LastCommand};
   465         $Stat{LastCommand} = $cl->{time};
   466         $Stat{TotalCommands}++;
   469 # Пропускаем строки, выходящие за границу "signature",
   470 # при условии, что границы указаны
   471 # Пропускаем неправильные/прерванные/другие команды
   472         if ($Config{"from"} && $cl->{"cline"} =~ /$Config{"signature"}\s*$Config{"from"}/) {
   473             $in_range=1;
   474             next;
   475         }
   476         if ($Config{"to"} && $cl->{"cline"} =~ /$Config{"signature"}\s*$Config{"to"}/) {
   477             $in_range=0;
   478             next;
   479         }
   480         next    if ($Config{"from"} && $Config{"to"}   && !$in_range) 
   481                 || ($Config{"skip_empty"} =~ /^y/i     && $cl->{"cline"} =~ /^\s*$/ )
   482                 || ($Config{"skip_wrong"} =~ /^y/i     && $cl->{"err"} != 0)
   483                 || ($Config{"skip_interrupted"} =~ /^y/i && $cl->{"err"} == 130);
   485         if ($cl->{class} eq "note") {
   486             my $note = $cl->{note};
   487             $note = join ("\n", map ("<p>$_</p>", split (/-\n/, $note)));
   488             $note =~ s@(http:[a-zA-Z.0-9/?\_%-]*)@<a href='$1'>$1</a>@g;
   489             $note =~ s@(www\.[a-zA-Z.0-9/?\_%-]*)@<a href='$1'>$1</a>@g;
   490             $this_day_result .= "<tr><td colspan='6'>"
   491                              .  "<h4 id='note$note_number'>".$cl->{note_title}."</h4>" if $cl->{note_title}
   492                              .  "".$note."<p/><p/></td></tr>";
   494             if ($cl->{note_title}) {
   495                 push @{$toc[@toc]},"<a href='#note$note_number'>".$cl->{note_title}."</a>";
   496                 $note_number++;
   497             }
   498             next;
   499         }
   502         my $output="";
   503 # Выводим <head_lines> верхних строк
   504 # и <tail_lines> нижних строк,
   505 # если эти параметры существуют
   507         if ($cl->{"last_command"} eq "cat" && !$cl->{"err"} && !($cl->{"cline"} =~ /</)) {
   508             my $filename = $cl->{"cline"};
   509             $filename =~ s/.*\s+(\S+)\s*$/$1/;
   510             $Files{$filename}->{"content"} = $cl->{"output"};
   511             $Files{$filename}->{"source_command_id"} = $cl->{"id"}
   512         }
   513         my @lines = split '\n', $cl->{"output"};
   514         if ((
   515              $Config{"head_lines"} 
   516              || $Config{"tail_lines"}
   517              )
   518              && $#lines >  $Config{"head_lines"} + $Config{"tail_lines"} ) {
   520             for (my $i=0; $i<= $#lines && $i < $Config{"head_lines"}; $i++) {
   521                 $output .= $lines[$i]."\n";
   522             }
   523             $output .= $Config{"skip_text"}."\n";
   525             my $start_line=$#lines-$Config{"tail_lines"}+1;
   526             for ($i=$start_line; $i<= $#lines; $i++) {
   527                 $output .= $lines[$i]."\n";
   528             }
   529         } 
   530         else {
   531            $ output .= $cl->{"output"};
   532         }   
   534 #
   535 ##
   536 ## Начинается собственно вывод
   537 ##
   538 #
   540         my ($sec,$min,$hour,$day,$mon,$year,$wday,$yday,$isdst) = localtime($cl->{time});
   542         # Добавляем спереди 0 для удобочитаемости
   543         $min  = "0".$min  if $min  =~ /^.$/;
   544         $hour = "0".$hour if $hour =~ /^.$/;
   545         $sec  = "0".$sec  if $sec  =~ /^.$/;
   547         $class=$cl->{"class"};
   548         $Stat{ErrorCommands}++          if $class =~ /wrong/;
   549         $Stat{MistypedCommands}++       if $class =~ /mistype/;
   552 # DAY CHANGE
   553         if ( $last_day ne $day) {
   554             if ($last_day) {
   556 # Вычисляем разность множеств.
   557 # Что-то вроде этого, если бы так можно было писать:
   558 #   @new_commands = keys %CommandsFDistribution - @known_commands;
   561                 $result .= "<h3 id='day$last_day'>".$Day_Name[$last_wday]."</h3>";
   565                 for my $entry_class (sort keys %new_entries_of) {
   566                     my $new_commands_section = make_new_entries_table($entry_class=~/[0-9]+\s+(.*)/, \@known_commands);
   568                     my $table_caption = "Таблица ".$table_number++.". ".$Day_Name[$last_wday].". Новые ".$new_entries_of{$entry_class};
   569                     if ($new_commands_section) {
   570                         $result .= "<table class='new_commands_table' width='700'>"
   571                                 .  "<tr class='new_commands_caption'><td colspan='2' align='right'>$table_caption</td></tr>"
   572                                 .  "<tr class='new_commands_header'><td width=100>Команда</td><td width=600>Описание</td></tr>"
   573                                 .  $new_commands_section 
   574                                 .  "</table>"
   575                     }
   577                 }
   578                 @known_commands = keys %CommandsFDistribution;
   579                 $result .= "<table width='100%'>\n";
   580                 $result .= $this_day_result;
   581                 $result .= "</table>";
   582             }
   584             push @toc, "<a href='#day$day'>".$Day_Name[$wday]."</a>\n";
   585             $last_day=$day;
   586             $last_wday=$wday;
   587             $this_day_result = q();
   588         }
   589         elsif ($seconds_since_last_command > 600) {
   590             my $height = $seconds_since_last_command > 1200 ? 100: 60;
   591             my $minutes_passed =  int($seconds_since_last_command/60);
   594             my $passed_word  = $minutes_passed % 10 == 1 ? "прошла"
   595                                                          : "прошло";
   596             my $minutes_word = $minutes_passed % 100 > 10 
   597                             && $minutes_passed % 100 < 20 ? "минут" :
   598                                $minutes_passed % 10 == 1 ? "минута":
   599                                $minutes_passed % 10 == 0 ? "минут" :
   600                                $minutes_passed % 10  > 4 ? "минут" :
   601                                                            "минуты";
   603             $this_day_result .= "<tr height='60'>"
   604                              .  "<td colspan='5' height='$height'>"
   605                              .  "<font size='-1'>"
   606                              .  $passed_word." ".$minutes_passed." ".$minutes_word
   607                              .  "</font>"
   608                              .  "</td></tr>\n";
   609         }
   611         $this_day_result .= "<tr class='command' id='command:".$cl->{"id"}."'>\n";
   614 # CONSOLE CHANGE
   615         if ( $last_tty ne $cl->{"tty"}) {
   616             my $tty = $cl->{"tty"};
   617             $this_day_result .= "<td colspan='6'>"
   618                                 ."<table><tr><td class='ttychange' width='140' align='center'>"
   619                                 . $tty
   620                                 ."</td></tr></table>"
   621                                 ."</td></tr><tr>";
   622             $last_tty=$cl->{"tty"};
   623         }
   625 # TIME
   626         $this_day_result .= $Config{"show_time"} =~ /^y/i
   627                  ? "<td width='100' valign='top' class='time' width='$Config{time_width}'>$hour:$min:$sec</td>"
   628                  : "<td width='0'/>";
   630 # CLASS
   631 #        if ($cl->{"err"}) {
   632 #            $this_day_result .= "<td width='6' valign='top'>"
   633 #                             .  "<table><tr><td width='6' height='6' class='err_box'>"
   634 #                             .  "E"
   635 #                             .  "</td></tr></table>"
   636 #                             .  "</td>";
   637 #        }
   638 #        else {
   639 #            $this_day_result .= "<td width='10' valign='top'>"
   640 #                             .  " "
   641 #                             .  "</td>";
   642 #        }
   644 # COMMAND
   645         my $hint = make_comment($cl->{"cline"});
   647         my $cline;
   648         $cline = $cl->{"prompt"}.$cl->{"cline"};
   649         $cline =~ s/\n//;
   651         $cline = "<span title='$hint' class='with_hint'>$cline</span>" if $hint;
   652         $cline = "<span class='without_hint'>$cline</span>" if !$hint;
   654         $this_day_result .= "<td class='script'>\n";
   655         $this_day_result .= "<pre class='${class}_cline'>\n" . $cline ;
   656         $this_day_result .= "<span title='Код завершения ".$cl->{"err"}."'> <img src='".$Config{frontend_ico_path}."/error.png'/></span>" if $cl->{"err"};
   657         $this_day_result .= "</pre>\n";
   659 # OUTPUT
   660         my $last_command = $cl->{"last_command"};
   661         if (!( 
   662         $Config{"suppress_editors"} =~ /^y/i && grep ($_ eq $last_command, @{$Config{"editors"}}) ||
   663         $Config{"suppress_pagers"}  =~ /^y/i && grep ($_ eq $last_command, @{$Config{"pagers"}}) ||
   664         $Config{"suppress_terminal"}=~ /^y/i && grep ($_ eq $last_command, @{$Config{"terminal"}})
   665             )) {
   666             $this_day_result .= "<pre class='".$class."_output'>" . $output . "</pre>\n";
   667         }   
   669 # DIFF
   670         if ( $Config{"show_diffs"} =~ /^y/i && $cl->{"diff"}) {
   671             $this_day_result .= "<table><tr><td width='5'/><td class='diff'><pre>"
   672                     .  $cl->{"diff"}
   673                     .  "</pre></td></tr></table>";
   674         }
   676 #NOTES
   677         if ( $Config{"show_notes"} =~ /^y/i && $cl->{"note"}) {
   678             my $note=$cl->{"note"};
   679             $note =~ s/\n/<br\/>\n/msg;
   680             if (not $note =~ s@(http:[a-zA-Z.0-9/_?%-]*)@<a href='$1'>$1</a>@g) {
   681               $note =~ s@(www\.[a-zA-Z.0-9/_?%-]*)@<a href='$1'>$1</a>@g;
   682             };
   683         #   Ширину пока не используем
   684         #   $this_day_result .= "<table width='$Config{note_width}' class='note'>";
   685             $this_day_result .= "<table class='note'>";
   686             $this_day_result .= "<tr><td class='note_title'>".$cl->{note_title}."</td></tr>" if $cl->{note_title};
   687             $this_day_result .= "<tr><td width='100%' class='note_text'>".$note."</td></tr>";
   688             $this_day_result .= "</table>\n";
   689         }
   691 # COMMENT
   692         if ( $Config{"show_comments"} =~ /^y/i) {
   693             my $comment = make_comment($cl->{"cline"});
   694             if ($comment) {
   695                 $this_day_result .= "<table width='$Config{comment_width}'><tr><td width='5'/><td>"
   696                         .  "<table class='note' width='100%'>"
   697                         .  $comment
   698                         .  "</table>\n"
   699                         .  "</td></tr></table>";
   700             }
   701         }
   703         # Вывод очередной команды окончен
   704         $this_day_result .= "</td>\n";
   705         $this_day_result .= "</tr>\n";
   706     }
   707     last: {
   708         $result .= "<h3 id='day$last_day'>".$Day_Name[$last_wday]."</h3>";
   710         for my $entry_class (keys %new_entries_of) {
   711             my $new_commands_section = make_new_entries_table("$entry_class", \@known_commands);
   712             @known_commands = keys %CommandsFDistribution;
   714             my $table_caption = "Таблица ".$table_number++.". Новые ".$new_entries_of{$entry_class}. ". ".$Day_Name[$last_wday];
   715             if ($new_commands_section) {
   716                 $result .= "<table class='new_commands_table'>"
   717                         .  "<tr class='new_commands_caption'><td colspan='2' align='right'>$table_caption</td></tr>"
   718                         .  "<tr class='new_commands_header'><td width='200'>Команда</td><td width='600'>Описание</td></tr>"
   719                         .  $new_commands_section 
   720                         .  "</table>"
   721                         ;
   722             }
   724         }
   726         $result .= "<table width='100%'>\n";
   727         $result .= $this_day_result;
   728         $result .= "</table>";
   729    }
   731     return ($result, collapse_list (\@toc));
   733 }
   735 sub make_new_entries_table
   736 {
   737     my $entries_class = shift;
   738     my @known_commands = @{$_[0]};
   740     my %count;
   741     my @new_commands = ();
   742     for my $c (keys %CommandsFDistribution, @known_commands) {
   743         $count{$c}++
   744     }
   745     for my $c (keys %CommandsFDistribution) {
   746         push @new_commands, $c if $count{$c} != 2;
   747     }
   750     my $new_commands_section;
   751     if (@new_commands){
   752         my $hint;
   753         for my $c (reverse sort { $CommandsFDistribution{$a} <=> $CommandsFDistribution{$b} } @new_commands) {
   754                 $hint = make_comment($c);
   755                 next unless $hint;
   756                 my ($command, $hint) = $hint =~ m/(.*?) \s*- \s*(.*)/;
   757                 next unless $command =~ s/\($entries_class\)//i;
   758                 $new_commands_section .= "<tr><td valign='top'>$command</td><td>$hint</td></tr>";
   759         }
   760     }
   761     return $new_commands_section;
   762 }
   765 #############
   766 # print_all
   767 #
   768 #
   769 #
   770 # In:       $_[0]       output_filename
   771 # Out:
   774 sub print_all
   775 {
   776     my $output_filename=$_[0];
   778     my $result;
   779     my ($command_lines,$toc)  = print_command_lines;
   780     my $files_section         = print_files;
   782     $result = print_header($toc);
   783     $result.= "<h2 id='log'>Журнал</h2>"       . $command_lines;
   784     $result.= "<h2 id='files'>Файлы</h2>"      . $files_section if $files_section;
   785     $result.= "<h2 id='stat'>Статистика</h2>"  . print_stat;
   786     $result.= "<h2 id='help'>Справка</h2>"     . $Html_Help . "<br/>"; 
   787     $result.= "<h2 id='about'>О программе</h2>". $Html_About. "<br/>"; 
   788     $result.= print_footer;
   790     if ($output_filename eq "-") {
   791         print $result;
   792     }
   793     else {
   794         open(OUT, ">", $output_filename)
   795             or die "Can't open $output_filename for writing\n";
   796         print OUT $result;
   797         close(OUT);
   798     }
   799 }
   801 #############
   802 # print_header
   803 #
   804 #
   805 #
   806 # In:   $_[0]       Содержание
   807 # Out:              Распечатанный заголовок
   809 sub print_header
   810 {
   811     my $toc = $_[0];
   812     my $course_name = $Config{"course-name"};
   813     my $course_code = $Config{"course-code"};
   814     my $course_date = $Config{"course-date"};
   815     my $course_center = $Config{"course-center"};
   816     my $course_trainer = $Config{"course-trainer"};
   817     my $course_student = $Config{"course-student"};
   819     my $title    = "Журнал лабораторных работ";
   820     $title      .= " -- ".$course_student if $course_student;
   821     if ($course_date) {
   822         $title  .= " -- ".$course_date; 
   823         $title  .= $course_code ? "/".$course_code 
   824                                 : "";
   825     }
   826     else {
   827         $title  .= " -- ".$course_code if $course_code;
   828     }
   830     # Управляющая форма
   831     my $control_form .= "<div class='visibility_form' title='Выберите какие элементы должны быть показаны в журнале'>"
   832                      .  "<span class='header'>Видимые элементы</span>"
   833                      .  "<span class='window_controls'><a href='' onclick='' title='свернуть форму управления'>_</a> <a href='' onclick='' title='закрыть форму управления'>x</a></span>"
   834                      .  "<div><form>\n";
   835     for my $element (sort keys %Elements_Visibility)
   836     {
   837         my ($skip, @e) = split /\s+/, $element;
   838         my $showhide = join "", map { "ShowHide('$_');" } @e ;
   839         $control_form .= "<div><input type='checkbox' name='$e[0]' onclick=\"$showhide\" checked>".
   840                 $Elements_Visibility{$element}.
   841                 "</input></div>";
   842     }
   843     $control_form .= "</form>\n"
   844                   .  "</div>\n";
   846     my $result;
   847     $result = <<HEADER;
   848     <html>
   849     <head>
   850     <meta content='text/html; charset=utf-8' http-equiv='Content-Type' />
   851     <link rel='stylesheet' href='$Config{frontend_css}' type='text/css'/>
   852     <title>$title</title>
   853     </head>
   854     <body>
   855     <script>
   856     $Html_JavaScript
   857     </script>
   859 <!-- vvv Tigra Hints vvv -->
   860 <script language="JavaScript" src="/tigra/hints.js"></script>
   861 <script language="JavaScript" src="/tigra/hints_cfg.js"></script>
   862 <style>
   863 /* a class for all Tigra Hints boxes, TD object */
   864     .hintsClass
   865         {text-align: center; font-family: Verdana, Arial, Helvetica; padding: 0px 0px 0px 0px;}
   866 /* this class is used by Tigra Hints wrappers */
   867     .row
   868         {background: white;}
   869 </style>
   870 <!-- ^^^ Tigra Hints ^^^ -->
   873     <h1 onmouseover="myHint.show('1')" onmouseout="myHint.hide()">Журнал лабораторных работ</h1>
   874 HEADER
   875     if (    $course_student 
   876             || $course_trainer 
   877             || $course_name 
   878             || $course_code 
   879             || $course_date 
   880             || $course_center) {
   881             $result .= "<p>";
   882             $result .= "Выполнил $course_student<br/>"  if $course_student;
   883             $result .= "Проверил $course_trainer <br/>" if $course_trainer;
   884             $result .= "Курс "                          if $course_name 
   885                                                             || $course_code 
   886                                                             || $course_date;
   887             $result .= "$course_name "                  if $course_name;
   888             $result .= "($course_code)"                 if $course_code;
   889             $result .= ", $course_date<br/>"            if $course_date;
   890             $result .= "Учебный центр $course_center <br/>" if $course_center;
   891             $result .= "</p>";
   892     }
   894     $result .= <<HEADER;
   895     <table width='100%'>
   896     <tr>
   897     <td width='*'>
   899     <table border=0 id='toc' class='toc'>
   900     <tr>
   901     <td>
   902     <div class='toc_title'>Содержание</div>
   903     <ul>
   904         <li><a href='#log'>Журнал</a></li>
   905         <ul>$toc</ul>
   906         <li><a href='#files'>Файлы</a></li>
   907         <li><a href='#stat'>Статистика</a></li>
   908         <li><a href='#help'>Справка</a></li>
   909         <li><a href='#about'>О программе</a></li>
   910     </ul>
   911     </td>
   912     </tr>
   913     </table>
   915     </td>
   916     <td valign='top' width=200>$control_form</td>
   917     </tr>
   918     </table>
   919 HEADER
   921     return $result;
   922 }
   925 #############
   926 # print_footer
   927 #
   928 #
   929 #
   930 #
   931 #
   933 sub print_footer
   934 {
   935     return "</body>\n</html>\n";
   936 }
   941 #############
   942 # print_stat
   943 #
   944 #
   945 #
   946 # In:
   947 # Out:
   949 sub print_stat
   950 {
   951     %StatNames = (
   952         FirstCommand        => "Время первой команды журнала",
   953         LastCommand         => "Время последней команды журнала",
   954         TotalCommands       => "Количество командных строк в журнале",
   955         ErrorsPercentage    => "Процент команд с ненулевым кодом завершения, %",
   956         MistypesPercentage  => "Процент синтаксически неверно набранных команд, %",
   957         TotalTime           => "Суммарное время работы с терминалом <sup><font size='-2'>*</font></sup>, час",
   958         CommandsPerTime     => "Количество командных строк в единицу времени, команда/мин",
   959         CommandsFrequency   => "Частота использования команд",
   960         RareCommands        => "Частота использования этих команд < 0.5%",
   961     );
   962     @StatOrder = (
   963         FirstCommand,
   964         LastCommand,
   965         TotalCommands,
   966         ErrorsPercentage,
   967         MistypesPercentage,
   968         TotalTime,
   969         CommandsPerTime,
   970         CommandsFrequency,
   971         RareCommands,
   972     );
   974     # Подготовка статистики к выводу
   975     # Некоторые значения пересчитываются!
   976     # Дальше их лучше уже не использовать!!!
   978     my %CommandsFrequency = %CommandsFDistribution;
   980     $Stat{TotalTime} ||= 0;
   981     my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($Stat{FirstCommand} || 0);
   982     $Stat{FirstCommand} = sprintf "%02i:%02i:%02i %04i-%2i-%2i", $hour, $min, $sec,  $year+1900, $mon+1, $mday;
   983     ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($Stat{LastCommand} || 0);
   984     $Stat{LastCommand} = sprintf "%02i:%02i:%02i %04i-%2i-%2i", $hour, $min, $sec,  $year+1900, $mon+1, $mday;
   985     if ($Stat{TotalCommands}) {
   986         $Stat{ErrorsPercentage} = sprintf "%5.2f", $Stat{ErrorCommands}*100/$Stat{TotalCommands};
   987         $Stat{MistypesPercentage} = sprintf "%5.2f", $Stat{MistypedCommands}*100/$Stat{TotalCommands};
   988     }
   989     $Stat{CommandsPerTime} = sprintf "%5.2f", $Stat{TotalCommands}*60/$Stat{TotalTime}
   990         if $Stat{TotalTime};
   991     $Stat{TotalTime} = sprintf "%5.2f", $Stat{TotalTime}/60/60;
   993     my $total_commands=0;
   994     for $command (keys %CommandsFrequency){
   995         $total_commands += $CommandsFrequency{$command};
   996     }
   997     if ($total_commands) {
   998         for $command (reverse sort {$CommandsFrequency{$a} <=> $CommandsFrequency{$b}} keys %CommandsFrequency){
   999             my $command_html;
  1000             my $percentage = sprintf "%5.2f",$CommandsFrequency{$command}*100/$total_commands;
  1001             if ($percentage < 0.5) {
  1002                 my $hint = make_comment($command);
  1003                 $command_html = "$command";
  1004                 $command_html = "<span title='$hint' class='with_hint'>$command_html</span>" if $hint;
  1005                 $command_html = "<span class='without_hint'>$command_html</span>" if not $hint;
  1006                 my $command_html = "<tt>$command_html</tt>";
  1007                 $Stat{RareCommands} .= $command_html."<sub><font size='-2'>".$CommandsFrequency{$command}."</font></sub> , ";
  1008             }
  1009             else {
  1010                 my $hint = make_comment($command);
  1011                 $command_html = "$command";
  1012                 $command_html = "<span title='$hint' class='with_hint'>$command_html</span>" if $hint;
  1013                 $command_html = "<span class='without_hint'>$command_html</span>" if not $hint;
  1014                 my $command_html = "<tt>$command_html</tt>";
  1015                 $percentage = sprintf "%5.2f",$percentage;
  1016                 $Stat{CommandsFrequency} .= "<tr><td>".$command_html."</td><td>".$CommandsFrequency{$command}."</td>".
  1017                     "<td>|".("="x int($CommandsFrequency{$command}*100/$total_commands))."| $percentage%</td></tr>";
  1018             }
  1019         }
  1020         $Stat{CommandsFrequency} = "<table>".$Stat{CommandsFrequency}."</table>";
  1021         $Stat{RareCommands} =~ s/, $// if $Stat{RareCommands};
  1022     }
  1024     my $result = q();
  1025     for my $stat (@StatOrder) {
  1026         next unless $Stat{"$stat"};
  1027         $result .= "<tr valign='top'><td width='300'>".$StatNames{"$stat"}."</td><td>".$Stat{"$stat"}."</td></tr>"
  1028     }
  1029     $result  = "<table>$result</table>"
  1030              . "<font size='-2'>____<br/>*) Интервалы неактивности длительностью "
  1031              .  ($Config{stat_inactivity_interval}/60)
  1032              . " минут и более не учитываются</font></br>";
  1034     return $result;
  1035 }
  1038 sub collapse_list($)
  1039 {
  1040     my $res = "";
  1041     for my $elem (@{$_[0]}) {
  1042         if (ref $elem eq "ARRAY") {
  1043             $res .= "<ul>".collapse_list($elem)."</ul>";
  1044         }
  1045         else
  1046         {
  1047             $res .= "<li>".$elem."</li>";
  1048         }
  1049     }
  1050     return $res;
  1051 }
  1054 sub print_files
  1055 {
  1056     my $result = qq(); 
  1057     my @toc;
  1058     for my $file (sort keys %Files) {
  1059           my $div_id = "file:$file";
  1060           $div_id =~ s@/@_@g;
  1061           push @toc, "<a href='#$div_id'>$file</a>";
  1062           $result .= "<div class='filename' id='$div_id'>".$file."</div>\n"
  1063                   .  "<div class='file_navigation'><a href='#command:".$Files{$file}->{source_command_id}."'>".">"."</a></div>"
  1064                   .  "<div class='filedata'><pre>".$Files{$file}->{content}."</pre></div>";
  1065     }
  1066     return "<div class='files_toc'>".collapse_list(\@toc)."</div>".$result;
  1067 }
  1070 sub init_variables
  1071 {
  1072 $Html_Help = <<HELP;
  1073     Для того чтобы использовать LiLaLo, не нужно знать ничего особенного:
  1074     всё происходит само собой.
  1075     Однако, чтобы ведение и последующее использование журналов
  1076     было как можно более эффективным, желательно иметь в виду следующее:
  1077     <ol>
  1078     <li><p> 
  1079     В журнал автоматически попадают все команды, данные в любом терминале системы.
  1080     </p></li>
  1081     <li><p>
  1082     Для того чтобы убедиться, что журнал на текущем терминале ведётся, 
  1083     и команды записываются, дайте команду w.
  1084     В поле WHAT, соответствующем текущему терминалу, 
  1085     должна быть указана программа script.
  1086     </p></li>
  1087     <li><p>
  1088     Команды, при наборе которых были допущены синтаксические ошибки, 
  1089     выводятся перечёркнутым текстом:
  1090 <table>
  1091 <tr class='command'>
  1092 <td class='script'>
  1093 <pre class='_mistyped_cline'>
  1094 \$ l s-l</pre>
  1095 <pre class='_mistyped_output'>bash: l: command not found
  1096 </pre>
  1097 </td>
  1098 </tr>
  1099 </table>
  1100 <br/>
  1101     </p></li>
  1102     <li><p>
  1103     Если код завершения команды равен нулю, 
  1104     команда была выполнена без ошибок.
  1105     Команды, код завершения которых отличен от нуля, выделяются цветом.
  1106 <table>
  1107 <tr class='command'>
  1108 <td class='script'>
  1109 <pre class='_wrong_cline'>
  1110 \$ test 5 -lt 4</pre>
  1111 </pre>
  1112 </td>
  1113 </tr>
  1114 </table>
  1115     Обратите внимание на то, что код завершения команды может быть отличен от нуля
  1116     не только в тех случаях, когда команда была выполнена с ошибкой.
  1117     Многие команды используют код завершения, например, для того чтобы показать результаты проверки
  1118 <br/>
  1119     </p></li>
  1120     <li><p>
  1121     Команды, ход выполнения которых был прерван пользователем, выделяются цветом.
  1122 <table>
  1123 <tr class='command'>
  1124 <td class='script'>
  1125 <pre class='_interrupted_cline'>
  1126 \$ find / -name abc</pre>
  1127 <pre class='interrupted_output'>find: /home/devi-orig/.gnome2: Keine Berechtigung
  1128 find: /home/devi-orig/.gnome2_private: Keine Berechtigung
  1129 find: /home/devi-orig/.nautilus/metafiles: Keine Berechtigung
  1130 find: /home/devi-orig/.metacity: Keine Berechtigung
  1131 find: /home/devi-orig/.inkscape: Keine Berechtigung
  1132 ^C
  1133 </pre>
  1134 </td>
  1135 </tr>
  1136 </table>
  1137 <br/>
  1138     </p></li>
  1139     <li><p>
  1140     Команды, выполненные с привилегиями суперпользователя,
  1141     выделяются слева красной чертой.
  1142 <table>
  1143 <tr class='command'>
  1144 <td class='script'>
  1145 <pre class='_root_cline'>
  1146 # id</pre>
  1147 <pre class='_root_output'>
  1148 uid=0(root) gid=0(root) Gruppen=0(root)
  1149 </pre>
  1150 </td>
  1151 </tr>
  1152 </table>
  1153     <br/>
  1154     </p></li>
  1155     <li><p>
  1156     Изменения, внесённые в текстовый файл с помощью редактора, 
  1157     запоминаются и показываются в журнале в формате ed.
  1158     Строки, начинающиеся символом "<", удалены, а строки,
  1159     начинающиеся символом ">" -- добавлены.
  1160 <table>
  1161 <tr class='command'>
  1162 <td class='script'>
  1163 <pre class='cline'>
  1164 \$ vi ~/.bashrc</pre>
  1165 <table><tr><td width='5'/><td class='diff'><pre>2a3,5
  1166 >    if [ -f /usr/local/etc/bash_completion ]; then
  1167 >         . /usr/local/etc/bash_completion
  1168 >        fi
  1169 </pre></td></tr></table></td>
  1170 </tr>
  1171 </table>
  1172     <br/>
  1173     </p></li>
  1174     <li><p>
  1175     Для того чтобы изменить файл в соответствии с показанными в диффшоте
  1176     изменениями, можно воспользоваться командой patch.
  1177     Нужно скопировать изменения, запустить программу patch, указав в
  1178     качестве её аргумента файл, к которому применяются изменения,
  1179     и всавить скопированный текст:
  1180 <table>
  1181 <tr class='command'>
  1182 <td class='script'>
  1183 <pre class='cline'>
  1184 \$ patch ~/.bashrc</pre>
  1185 </td>
  1186 </tr>
  1187 </table>
  1188     В данном случае изменения применяются к файлу ~/.bashrc
  1189     </p></li>
  1190     <li><p>
  1191     Для того чтобы получить краткую справочную информацию о команде, 
  1192     нужно подвести к ней мышь. Во всплывающей подсказке появится краткое
  1193     описание команды.
  1194     </p>
  1195     <p>
  1196     Если справочная информация о команде есть, 
  1197     команда выделяется голубым фоном, например: <span class="with_hint" title="главный текстовый редактор Unix">vi</span>.
  1198     Если справочная информация отсутствует,
  1199     команда выделяется розовым фоном, например: <span class="without_hint">notepad.exe</span>.
  1200     Справочная информация может отсутствовать в том случае, 
  1201     если (1) команда введена неверно; (2) если распознавание команды LiLaLo выполнено неверно;
  1202     (3) если информация о команде неизвестна LiLaLo.
  1203     Последнее возможно для редких команд.
  1204     </p></li>
  1205     <li><p>
  1206     Большие, в особенности многострочные, всплывающие подсказки лучше 
  1207     всего показываются браузерами KDE Konqueror, Apple Safari и Microsoft Internet Explorer.
  1208     В браузерах Mozilla и Firefox они отображаются не полностью, 
  1209     а вместо перевода строки выводится специальный символ.
  1210     </p></li>
  1211     <li><p>
  1212     Время ввода команды, показанное в журнале, соответствует времени 
  1213     <i>начала ввода командной строки</i>, которое равно тому моменту, 
  1214     когда на терминале появилось приглашение интерпретатора
  1215     </p></li>
  1216     <li><p>
  1217     Имя терминала, на котором была введена команда, показано в специальном блоке.
  1218     Этот блок показывается только в том случае, если терминал
  1219     текущей команды отличается от терминала предыдущей.
  1220     </p></li>
  1221     <li><p>
  1222     Вывод не интересующих вас в настоящий момент элементов журнала,
  1223     таких как время, имя терминала и других, можно отключить.
  1224     Для этого нужно воспользоваться <a href='#visibility_form'>формой управления журналом</a>
  1225     вверху страницы.
  1226     </p></li>
  1227     <li><p>
  1228     Небольшие комментарии к командам можно вставлять прямо из командной строки.
  1229     Комментарий вводится прямо в командную строку, после символов #^ или #v.
  1230     Символы ^ и v показывают направление выбора команды, к которой относится комментарий:
  1231     ^ - к предыдущей, v - к следующей.
  1232     Например, если в командной строке было введено:
  1233 <pre class='cline'>
  1234 \$ whoami
  1235 </pre>
  1236 <pre class='output'>
  1237 user
  1238 </pre>
  1239 <pre class='cline'>
  1240 \$ #^ Интересно, кто я?
  1241 </pre>
  1242     в журнале это будет выглядеть так:
  1244 <pre class='cline'>
  1245 \$ whoami
  1246 </pre>
  1247 <pre class='output'>
  1248 user
  1249 </pre>
  1250 <table class='note'><tr><td width='100%' class='note_text'>
  1251 <tr> <td> Интересно, кто я?<br/> </td></tr></table> 
  1252     </p></li>
  1253     <li><p>
  1254     Если комментарий содержит несколько строк,
  1255     его можно вставить в журнал следующим образом:
  1256 <pre class='cline'>
  1257 \$ whoami
  1258 </pre>
  1259 <pre class='output'>
  1260 user
  1261 </pre>
  1262 <pre class='cline'>
  1263 \$ cat > /dev/null #^ Интересно, кто я?
  1264 </pre>
  1265 <pre class='output'>
  1266 Программа whoami выводит имя пользователя, под которым 
  1267 мы зарегистрировались в системе.
  1268 -
  1269 Она не может ответить на вопрос о нашем назначении 
  1270 в этом мире.
  1271 </pre>
  1272     В журнале это будет выглядеть так:
  1273 <table>
  1274 <tr class='command'>
  1275 <td class='script'>
  1276 <pre class='cline'>
  1277 \$ whoami</pre>
  1278 <pre class='output'>user
  1279 </pre>
  1280 <table class='note'><tr><td class='note_title'>Интересно, кто я?</td></tr><tr><td width='100%' class='note_text'>
  1281 Программа whoami выводит имя пользователя, под которым<br/>
  1282 мы зарегистрировались в системе.<br/>
  1283 <br/>
  1284 Она не может ответить на вопрос о нашем назначении<br/>
  1285 в этом мире.<br/>
  1286 </td></tr></table>
  1287 </td>
  1288 </tr>
  1289 </table>
  1290     Для разделения нескольких абзацев между собой
  1291     используйте символ "-", один в строке.
  1292     <br/>
  1293 </p></li>
  1294     <li><p>
  1295     Комментарии, не относящиеся непосредственно ни к какой из команд, 
  1296     добавляются точно таким же способом, только вместо симолов #^ или #v 
  1297     нужно использовать символы #=
  1298     </p></li>
  1299 </ol>
  1300 HELP
  1302 $Html_About = <<ABOUT;
  1303     <p>
  1304     LiLaLo (L3) расшифровывается как Live Lab Log.<br/>
  1305     Программа разработана для повышения эффективности обучения Unix/Linux-системам.<br/>
  1306     (c) Игорь Чубин, 2004-2006<br/>
  1307     </p>
  1308 ABOUT
  1309 $Html_About.='$Id$ </p>';
  1311 $Html_JavaScript = <<JS;
  1312     function getElementsByClassName(Class_Name)
  1313     {
  1314         var Result=new Array();
  1315         var All_Elements=document.all || document.getElementsByTagName('*');
  1316         for (i=0; i<All_Elements.length; i++)
  1317             if (All_Elements[i].className==Class_Name)
  1318         Result.push(All_Elements[i]);
  1319         return Result;
  1320     }
  1321     function ShowHide (name)
  1322     {
  1323         elements=getElementsByClassName(name);
  1324         for(i=0; i<elements.length; i++)
  1325             if (elements[i].style.display == "none")
  1326                 elements[i].style.display = "";
  1327             else
  1328                 elements[i].style.display = "none";
  1329             //if (elements[i].style.visibility == "hidden")
  1330             //  elements[i].style.visibility = "visible";
  1331             //else
  1332             //  elements[i].style.visibility = "hidden";
  1333     }
  1334     function filter_by_output(text)
  1335     {
  1337         var jjj=0;
  1339         elements=getElementsByClassName('command');
  1340         for(i=0; i<elements.length; i++) {
  1341             subelems = elements[i].getElementsByTagName('pre');
  1342             for(j=0; j<subelems.length; j++) {
  1343                 if (subelems[j].className = 'output') {
  1344                     var str = new String(subelems[j].nodeValue);
  1345                     if (jjj != 1) { 
  1346                         alert(str);
  1347                         jjj=1;
  1348                     }
  1349                     if (str.indexOf(text) >0) 
  1350                         subelems[j].style.display = "none";
  1351                     else
  1352                         subelems[j].style.display = "";
  1354                 }
  1356             }
  1357         }       
  1359     }
  1360 JS
  1362 %Search_Machines = (
  1363         "google" =>     {   "query" =>  "http://www.google.com/search?q=" ,
  1364                     "icon"  =>  "$Config{frontend_google_ico}" },
  1365         "freebsd" =>    {   "query" =>  "http://www.freebsd.org/cgi/man.cgi?query=",
  1366                     "icon"  =>  "$Config{frontend_freebsd_ico}" },
  1367         "linux"  =>     {   "query" =>  "http://man.he.net/?topic=",
  1368                     "icon"  =>  "$Config{frontend_linux_ico}"},
  1369         "opennet"  =>   {   "query" =>  "http://www.opennet.ru/search.shtml?words=",
  1370                     "icon"  =>  "$Config{frontend_opennet_ico}"},
  1371         "local" =>  {   "query" =>  "http://www.freebsd.org/cgi/man.cgi?query=",
  1372                     "icon"  =>  "$Config{frontend_local_ico}" },
  1374     );
  1376 %Elements_Visibility = (
  1377         "0 new_commands_table"      =>  "новые команды",
  1378         "1 diff"      =>  "редактор",
  1379         "2 time"      =>  "время",
  1380         "3 ttychange"     =>  "терминал",
  1381         "4 wrong_output wrong_cline wrong_root_output wrong_root_cline" 
  1382                 =>  "команды с ненулевым кодом завершения",
  1383         "5 mistyped_output mistyped_cline mistyped_root_output mistyped_root_cline" 
  1384                 =>  "неверно набранные команды",
  1385         "6 interrupted_output interrupted_cline interrupted_root_output interrupted_root_cline" 
  1386                 =>  "прерванные команды",
  1387         "7 tab_completion_output tab_completion_cline"    
  1388                 =>  "продолжение с помощью tab"
  1389 );
  1391 @Day_Name      = qw/ Воскресенье Понедельник Вторник Среда Четверг Пятница Суббота /;
  1392 @Month_Name    = qw/ Январь Февраль Март Апрель Май Июнь Июль Август Сентябрь Октябрь Ноябрь Декабрь /;
  1393 @Of_Month_Name = qw/ Января Февраля Марта Апреля Мая Июня Июля Августа Сентября Октября Ноября Декабря /;
  1394 }
  1399 # Временно удалённый код
  1400 # Возможно, он не понадобится уже никогда
  1403 sub search_by
  1404 {
  1405     my $sm = shift;
  1406     my $topic = shift;
  1407     $topic =~ s/ /+/;
  1409     return "<a href='". $Search_Machines{$sm}->{"query"}."$topic'><img width='16' height='16' src='".
  1410                 $Search_Machines{$sm}->{"icon"}."' border='0'/></a>";
  1411 }
