lilalo
view l3-frontend @ 77:e56f21c44faf
Под root'ом приглашение красного цвета
| author | devi | 
|---|---|
| date | Mon Feb 13 19:28:51 2006 +0200 (2006-02-13) | 
| parents | 35e0d61c820d | 
| children | d28dda8ea18f | 
 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' cellspacing='0' cellpadding='0'>"
   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 > 7200) {
   590             my $hours_passed =  int($seconds_since_last_command/3600);
   591             my $passed_word  = $minutes_passed % 10 == 1 ? "прошла"
   592                                                          : "прошло";
   593             my $hours_word   = $hours_passed % 10 == 1 ?   "часа":
   594                                                            "часов";
   595             $this_day_result .= "<div class='much_time_passed'>"
   596                              .  $passed_word." >".$hours_passed." ".$hours_word
   597                              .  "</div>\n";
   598         }
   599         elsif ($seconds_since_last_command > 600) {
   600             my $minutes_passed =  int($seconds_since_last_command/60);
   603             my $passed_word  = $minutes_passed % 100 > 10 
   604                             && $minutes_passed % 100 < 20 ? "прошло"
   605                              : $minutes_passed % 10 == 1  ? "прошла"
   606                                                           : "прошло";
   608             my $minutes_word = $minutes_passed % 100 > 10 
   609                             && $minutes_passed % 100 < 20 ? "минут" :
   610                                $minutes_passed % 10 == 1 ? "минута":
   611                                $minutes_passed % 10 == 0 ? "минут" :
   612                                $minutes_passed % 10  > 4 ? "минут" :
   613                                                            "минуты";
   615             if ($seconds_since_last_command < 1800) {
   616             $this_day_result .= "<div class='time_passed'>"
   617                              .  $passed_word." ".$minutes_passed." ".$minutes_word
   618                              .  "</div>\n";
   619             }
   620             else {
   621             $this_day_result .= "<div class='much_time_passed'>"
   622                              .  $passed_word." ".$minutes_passed." ".$minutes_word
   623                              .  "</div>\n";
   624             }
   625         }
   627         #$this_day_result .= "<table cellspacing='0' cellpading='0' class='command' id='command:".$cl->{"id"}."' width='100%'><tr>\n";
   628         $this_day_result .= "<div class='command' id='command:".$cl->{"id"}."' >\n";
   631 # CONSOLE CHANGE
   632         if ( $last_tty ne $cl->{"tty"} && 0) {
   633             my $tty = $cl->{"tty"};
   634             $this_day_result .= "<div class='ttychange'>"
   635                                 . $tty
   636                                 ."</div>";
   637             $last_tty=$cl->{"tty"};
   638         }
   640 # TIME
   641         $this_day_result .= "<div class='time'>$hour:$min:$sec</div>" 
   642                             if $Config{"show_time"} =~ /^y/i;
   644         #$this_day_result .= $Config{"show_time"} =~ /^y/i
   645         #         ? "<td width='100' valign='top' class='time' width='$Config{time_width}'>$hour:$min:$sec</td>"
   646         #         : "<td width='0'/>";
   648 # CLASS
   649 #        if ($cl->{"err"}) {
   650 #            $this_day_result .= "<td width='6' valign='top'>"
   651 #                             .  "<table><tr><td width='6' height='6' class='err_box'>"
   652 #                             .  "E"
   653 #                             .  "</td></tr></table>"
   654 #                             .  "</td>";
   655 #        }
   656 #        else {
   657 #            $this_day_result .= "<td width='10' valign='top'>"
   658 #                             .  " "
   659 #                             .  "</td>";
   660 #        }
   662 # COMMAND
   663         my $hint = make_comment($cl->{"cline"});
   665         my $cline;
   666         $cline = $cl->{"prompt"}.$cl->{"cline"};
   667         $cline =~ s/\n//;
   669         $cline = "<span title='$hint' class='with_hint'>$cline</span>" if $hint;
   670         $cline = "<span class='without_hint'>$cline</span>" if !$hint;
   672         $this_day_result .= "<table cellpadding='0' cellspacing='0'><tr><td>\n<div class='cblock_$cl->{class}'>\n";
   673         $this_day_result .= "<div class='cline'>\n" . $cline ;      #cline
   674         $this_day_result .= "<span title='Код завершения ".$cl->{"err"}."'>\n"
   675                          .  "<img src='".$Config{frontend_ico_path}."/error.png'/>\n"
   676                          .  "</span>\n" if $cl->{"err"};
   677         $this_day_result .= "</div>\n";                             #cline
   679 # OUTPUT
   680         my $last_command = $cl->{"last_command"};
   681         if (!( 
   682         $Config{"suppress_editors"} =~ /^y/i && grep ($_ eq $last_command, @{$Config{"editors"}}) ||
   683         $Config{"suppress_pagers"}  =~ /^y/i && grep ($_ eq $last_command, @{$Config{"pagers"}}) ||
   684         $Config{"suppress_terminal"}=~ /^y/i && grep ($_ eq $last_command, @{$Config{"terminal"}})
   685             )) {
   686             $this_day_result .= "<pre class='output'>\n" . $output . "</pre>\n";
   687         }   
   689 # DIFF
   690         $this_day_result .= "<pre class='diff'>".$cl->{"diff"}."</pre>"
   691             if ( $Config{"show_diffs"} =~ /^y/i && $cl->{"diff"});
   693 #NOTES
   694         if ( $Config{"show_notes"} =~ /^y/i && $cl->{"note"}) {
   695             my $note=$cl->{"note"};
   696             $note =~ s/\n/<br\/>\n/msg;
   697             if (not $note =~ s@(http:[a-zA-Z.0-9/_?%-]*)@<a href='$1'>$1</a>@g) {
   698               $note =~ s@(www\.[a-zA-Z.0-9/_?%-]*)@<a href='$1'>$1</a>@g;
   699             };
   700             $this_day_result .= "<div class='note'>";
   701             $this_day_result .= "<div class='note_title'>".$cl->{note_title}."</div>" if $cl->{note_title};
   702             $this_day_result .= "<div class='note_text'>".$note."</div>";
   703             $this_day_result .= "</div>\n";
   704         }
   706 # COMMENT
   707         if ( $Config{"show_comments"} =~ /^y/i) {
   708             my $comment = make_comment($cl->{"cline"});
   709             if ($comment) {
   710                 $this_day_result .= 
   711                            "<div class='note' width='100%'>"
   712                         .  $comment
   713                         .  "</div>\n"
   714                         ;
   716             }
   717         }
   719         # Вывод очередной команды окончен
   720         $this_day_result .= "</div>\n";                     # cblock
   721         $this_day_result .= "</td></tr></table>\n"
   722                          .  "</div>\n";                     # command
   723     }
   724     last: {
   725         $result .= "<h3 id='day$last_day'>".$Day_Name[$last_wday]."</h3>";
   727         for my $entry_class (keys %new_entries_of) {
   728             my $new_commands_section = make_new_entries_table("$entry_class", \@known_commands);
   729             @known_commands = keys %CommandsFDistribution;
   731             my $table_caption = "Таблица ".$table_number++.". Новые ".$new_entries_of{$entry_class}. ". ".$Day_Name[$last_wday];
   732             if ($new_commands_section) {
   733                 $result .= "<table class='new_commands_table'>"
   734                         .  "<tr class='new_commands_caption'><td colspan='2' align='right'>$table_caption</td></tr>"
   735                         .  "<tr class='new_commands_header'><td width='200'>Команда</td><td width='600'>Описание</td></tr>"
   736                         .  $new_commands_section 
   737                         .  "</table>"
   738                         ;
   739             }
   741         }
   743         #$result .= "<table width='100%'>\n";
   744         $result .= $this_day_result;
   745         #$result .= "</table>";
   746    }
   748     return ($result, collapse_list (\@toc));
   750 }
   752 sub make_new_entries_table
   753 {
   754     my $entries_class = shift;
   755     my @known_commands = @{$_[0]};
   757     my %count;
   758     my @new_commands = ();
   759     for my $c (keys %CommandsFDistribution, @known_commands) {
   760         $count{$c}++
   761     }
   762     for my $c (keys %CommandsFDistribution) {
   763         push @new_commands, $c if $count{$c} != 2;
   764     }
   767     my $new_commands_section;
   768     if (@new_commands){
   769         my $hint;
   770         for my $c (reverse sort { $CommandsFDistribution{$a} <=> $CommandsFDistribution{$b} } @new_commands) {
   771                 $hint = make_comment($c);
   772                 next unless $hint;
   773                 my ($command, $hint) = $hint =~ m/(.*?) \s*- \s*(.*)/;
   774                 next unless $command =~ s/\($entries_class\)//i;
   775                 $new_commands_section .= "<tr><td valign='top'>$command</td><td>$hint</td></tr>";
   776         }
   777     }
   778     return $new_commands_section;
   779 }
   782 #############
   783 # print_all
   784 #
   785 #
   786 #
   787 # In:       $_[0]       output_filename
   788 # Out:
   791 sub print_all
   792 {
   793     my $output_filename=$_[0];
   795     my $result;
   796     my ($command_lines,$toc)  = print_command_lines;
   797     my $files_section         = print_files;
   799     $result = print_header($toc);
   800     $result.= "<h2 id='log'>Журнал</h2>"       . $command_lines;
   801     $result.= "<h2 id='files'>Файлы</h2>"      . $files_section if $files_section;
   802     $result.= "<h2 id='stat'>Статистика</h2>"  . print_stat;
   803     $result.= "<h2 id='help'>Справка</h2>"     . $Html_Help . "<br/>"; 
   804     $result.= "<h2 id='about'>О программе</h2>". $Html_About. "<br/>"; 
   805     $result.= print_footer;
   807     if ($output_filename eq "-") {
   808         print $result;
   809     }
   810     else {
   811         open(OUT, ">", $output_filename)
   812             or die "Can't open $output_filename for writing\n";
   813         print OUT $result;
   814         close(OUT);
   815     }
   816 }
   818 #############
   819 # print_header
   820 #
   821 #
   822 #
   823 # In:   $_[0]       Содержание
   824 # Out:              Распечатанный заголовок
   826 sub print_header
   827 {
   828     my $toc = $_[0];
   829     my $course_name = $Config{"course-name"};
   830     my $course_code = $Config{"course-code"};
   831     my $course_date = $Config{"course-date"};
   832     my $course_center = $Config{"course-center"};
   833     my $course_trainer = $Config{"course-trainer"};
   834     my $course_student = $Config{"course-student"};
   836     my $title    = "Журнал лабораторных работ";
   837     $title      .= " -- ".$course_student if $course_student;
   838     if ($course_date) {
   839         $title  .= " -- ".$course_date; 
   840         $title  .= $course_code ? "/".$course_code 
   841                                 : "";
   842     }
   843     else {
   844         $title  .= " -- ".$course_code if $course_code;
   845     }
   847     # Управляющая форма
   848     my $control_form .= "<div class='visibility_form' title='Выберите какие элементы должны быть показаны в журнале'>"
   849                      .  "<span class='header'>Видимые элементы</span>"
   850                      .  "<span class='window_controls'><a href='' onclick='' title='свернуть форму управления'>_</a> <a href='' onclick='' title='закрыть форму управления'>x</a></span>"
   851                      .  "<div><form>\n";
   852     for my $element (sort keys %Elements_Visibility)
   853     {
   854         my ($skip, @e) = split /\s+/, $element;
   855         my $showhide = join "", map { "ShowHide('$_');" } @e ;
   856         $control_form .= "<div><input type='checkbox' name='$e[0]' onclick=\"$showhide\" checked>".
   857                 $Elements_Visibility{$element}.
   858                 "</input></div>";
   859     }
   860     $control_form .= "</form>\n"
   861                   .  "</div>\n";
   863     my $result;
   864     $result = <<HEADER;
   865     <html>
   866     <head>
   867     <meta content='text/html; charset=utf-8' http-equiv='Content-Type' />
   868     <link rel='stylesheet' href='$Config{frontend_css}' type='text/css'/>
   869     <title>$title</title>
   870     </head>
   871     <body>
   872     <script>
   873     $Html_JavaScript
   874     </script>
   876 <!-- vvv Tigra Hints vvv -->
   877 <script language="JavaScript" src="/tigra/hints.js"></script>
   878 <script language="JavaScript" src="/tigra/hints_cfg.js"></script>
   879 <style>
   880 /* a class for all Tigra Hints boxes, TD object */
   881     .hintsClass
   882         {text-align: center; font-family: Verdana, Arial, Helvetica; padding: 0px 0px 0px 0px;}
   883 /* this class is used by Tigra Hints wrappers */
   884     .row
   885         {background: white;}
   886 </style>
   887 <!-- ^^^ Tigra Hints ^^^ -->
   890     <h1 onmouseover="myHint.show('1')" onmouseout="myHint.hide()">Журнал лабораторных работ</h1>
   891 HEADER
   892     if (    $course_student 
   893             || $course_trainer 
   894             || $course_name 
   895             || $course_code 
   896             || $course_date 
   897             || $course_center) {
   898             $result .= "<p>";
   899             $result .= "Выполнил $course_student<br/>"  if $course_student;
   900             $result .= "Проверил $course_trainer <br/>" if $course_trainer;
   901             $result .= "Курс "                          if $course_name 
   902                                                             || $course_code 
   903                                                             || $course_date;
   904             $result .= "$course_name "                  if $course_name;
   905             $result .= "($course_code)"                 if $course_code;
   906             $result .= ", $course_date<br/>"            if $course_date;
   907             $result .= "Учебный центр $course_center <br/>" if $course_center;
   908             $result .= "</p>";
   909     }
   911     $result .= <<HEADER;
   912     <table width='100%'>
   913     <tr>
   914     <td width='*'>
   916     <table border=0 id='toc' class='toc'>
   917     <tr>
   918     <td>
   919     <div class='toc_title'>Содержание</div>
   920     <ul>
   921         <li><a href='#log'>Журнал</a></li>
   922         <ul>$toc</ul>
   923         <li><a href='#files'>Файлы</a></li>
   924         <li><a href='#stat'>Статистика</a></li>
   925         <li><a href='#help'>Справка</a></li>
   926         <li><a href='#about'>О программе</a></li>
   927     </ul>
   928     </td>
   929     </tr>
   930     </table>
   932     </td>
   933     <td valign='top' width=200>$control_form</td>
   934     </tr>
   935     </table>
   936 HEADER
   938     return $result;
   939 }
   942 #############
   943 # print_footer
   944 #
   945 #
   946 #
   947 #
   948 #
   950 sub print_footer
   951 {
   952     return "</body>\n</html>\n";
   953 }
   958 #############
   959 # print_stat
   960 #
   961 #
   962 #
   963 # In:
   964 # Out:
   966 sub print_stat
   967 {
   968     %StatNames = (
   969         FirstCommand        => "Время первой команды журнала",
   970         LastCommand         => "Время последней команды журнала",
   971         TotalCommands       => "Количество командных строк в журнале",
   972         ErrorsPercentage    => "Процент команд с ненулевым кодом завершения, %",
   973         MistypesPercentage  => "Процент синтаксически неверно набранных команд, %",
   974         TotalTime           => "Суммарное время работы с терминалом <sup><font size='-2'>*</font></sup>, час",
   975         CommandsPerTime     => "Количество командных строк в единицу времени, команда/мин",
   976         CommandsFrequency   => "Частота использования команд",
   977         RareCommands        => "Частота использования этих команд < 0.5%",
   978     );
   979     @StatOrder = (
   980         FirstCommand,
   981         LastCommand,
   982         TotalCommands,
   983         ErrorsPercentage,
   984         MistypesPercentage,
   985         TotalTime,
   986         CommandsPerTime,
   987         CommandsFrequency,
   988         RareCommands,
   989     );
   991     # Подготовка статистики к выводу
   992     # Некоторые значения пересчитываются!
   993     # Дальше их лучше уже не использовать!!!
   995     my %CommandsFrequency = %CommandsFDistribution;
   997     $Stat{TotalTime} ||= 0;
   998     my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($Stat{FirstCommand} || 0);
   999     $Stat{FirstCommand} = sprintf "%02i:%02i:%02i %04i-%2i-%2i", $hour, $min, $sec,  $year+1900, $mon+1, $mday;
  1000     ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($Stat{LastCommand} || 0);
  1001     $Stat{LastCommand} = sprintf "%02i:%02i:%02i %04i-%2i-%2i", $hour, $min, $sec,  $year+1900, $mon+1, $mday;
  1002     if ($Stat{TotalCommands}) {
  1003         $Stat{ErrorsPercentage} = sprintf "%5.2f", $Stat{ErrorCommands}*100/$Stat{TotalCommands};
  1004         $Stat{MistypesPercentage} = sprintf "%5.2f", $Stat{MistypedCommands}*100/$Stat{TotalCommands};
  1005     }
  1006     $Stat{CommandsPerTime} = sprintf "%5.2f", $Stat{TotalCommands}*60/$Stat{TotalTime}
  1007         if $Stat{TotalTime};
  1008     $Stat{TotalTime} = sprintf "%5.2f", $Stat{TotalTime}/60/60;
  1010     my $total_commands=0;
  1011     for $command (keys %CommandsFrequency){
  1012         $total_commands += $CommandsFrequency{$command};
  1013     }
  1014     if ($total_commands) {
  1015         for $command (reverse sort {$CommandsFrequency{$a} <=> $CommandsFrequency{$b}} keys %CommandsFrequency){
  1016             my $command_html;
  1017             my $percentage = sprintf "%5.2f",$CommandsFrequency{$command}*100/$total_commands;
  1018             if ($percentage < 0.5) {
  1019                 my $hint = make_comment($command);
  1020                 $command_html = "$command";
  1021                 $command_html = "<span title='$hint' class='with_hint'>$command_html</span>" if $hint;
  1022                 $command_html = "<span class='without_hint'>$command_html</span>" if not $hint;
  1023                 my $command_html = "<tt>$command_html</tt>";
  1024                 $Stat{RareCommands} .= $command_html."<sub><font size='-2'>".$CommandsFrequency{$command}."</font></sub> , ";
  1025             }
  1026             else {
  1027                 my $hint = make_comment($command);
  1028                 $command_html = "$command";
  1029                 $command_html = "<span title='$hint' class='with_hint'>$command_html</span>" if $hint;
  1030                 $command_html = "<span class='without_hint'>$command_html</span>" if not $hint;
  1031                 my $command_html = "<tt>$command_html</tt>";
  1032                 $percentage = sprintf "%5.2f",$percentage;
  1033                 $Stat{CommandsFrequency} .= "<tr><td>".$command_html."</td><td>".$CommandsFrequency{$command}."</td>".
  1034                     "<td>|".("="x int($CommandsFrequency{$command}*100/$total_commands))."| $percentage%</td></tr>";
  1035             }
  1036         }
  1037         $Stat{CommandsFrequency} = "<table>".$Stat{CommandsFrequency}."</table>";
  1038         $Stat{RareCommands} =~ s/, $// if $Stat{RareCommands};
  1039     }
  1041     my $result = q();
  1042     for my $stat (@StatOrder) {
  1043         next unless $Stat{"$stat"};
  1044         $result .= "<tr valign='top'><td width='300'>".$StatNames{"$stat"}."</td><td>".$Stat{"$stat"}."</td></tr>"
  1045     }
  1046     $result  = "<table>$result</table>"
  1047              . "<font size='-2'>____<br/>*) Интервалы неактивности длительностью "
  1048              .  ($Config{stat_inactivity_interval}/60)
  1049              . " минут и более не учитываются</font></br>";
  1051     return $result;
  1052 }
  1055 sub collapse_list($)
  1056 {
  1057     my $res = "";
  1058     for my $elem (@{$_[0]}) {
  1059         if (ref $elem eq "ARRAY") {
  1060             $res .= "<ul>".collapse_list($elem)."</ul>";
  1061         }
  1062         else
  1063         {
  1064             $res .= "<li>".$elem."</li>";
  1065         }
  1066     }
  1067     return $res;
  1068 }
  1071 sub print_files
  1072 {
  1073     my $result = qq(); 
  1074     my @toc;
  1075     for my $file (sort keys %Files) {
  1076           my $div_id = "file:$file";
  1077           $div_id =~ s@/@_@g;
  1078           push @toc, "<a href='#$div_id'>$file</a>";
  1079           $result .= "<div class='filename' id='$div_id'>".$file."</div>\n"
  1080                   .  "<div class='file_navigation'><a href='#command:".$Files{$file}->{source_command_id}."'>".">"."</a></div>"
  1081                   .  "<div class='filedata'><pre>".$Files{$file}->{content}."</pre></div>";
  1082     }
  1083     return "<div class='files_toc'>".collapse_list(\@toc)."</div>".$result;
  1084 }
  1087 sub init_variables
  1088 {
  1089 $Html_Help = <<HELP;
  1090     Для того чтобы использовать LiLaLo, не нужно знать ничего особенного:
  1091     всё происходит само собой.
  1092     Однако, чтобы ведение и последующее использование журналов
  1093     было как можно более эффективным, желательно иметь в виду следующее:
  1094     <ol>
  1095     <li><p> 
  1096     В журнал автоматически попадают все команды, данные в любом терминале системы.
  1097     </p></li>
  1098     <li><p>
  1099     Для того чтобы убедиться, что журнал на текущем терминале ведётся, 
  1100     и команды записываются, дайте команду w.
  1101     В поле WHAT, соответствующем текущему терминалу, 
  1102     должна быть указана программа script.
  1103     </p></li>
  1104     <li><p>
  1105     Команды, при наборе которых были допущены синтаксические ошибки, 
  1106     выводятся перечёркнутым текстом:
  1107 <table>
  1108 <tr class='command'>
  1109 <td class='script'>
  1110 <pre class='_mistyped_cline'>
  1111 \$ l s-l</pre>
  1112 <pre class='_mistyped_output'>bash: l: command not found
  1113 </pre>
  1114 </td>
  1115 </tr>
  1116 </table>
  1117 <br/>
  1118     </p></li>
  1119     <li><p>
  1120     Если код завершения команды равен нулю, 
  1121     команда была выполнена без ошибок.
  1122     Команды, код завершения которых отличен от нуля, выделяются цветом.
  1123 <table>
  1124 <tr class='command'>
  1125 <td class='script'>
  1126 <pre class='_wrong_cline'>
  1127 \$ test 5 -lt 4</pre>
  1128 </pre>
  1129 </td>
  1130 </tr>
  1131 </table>
  1132     Обратите внимание на то, что код завершения команды может быть отличен от нуля
  1133     не только в тех случаях, когда команда была выполнена с ошибкой.
  1134     Многие команды используют код завершения, например, для того чтобы показать результаты проверки
  1135 <br/>
  1136     </p></li>
  1137     <li><p>
  1138     Команды, ход выполнения которых был прерван пользователем, выделяются цветом.
  1139 <table>
  1140 <tr class='command'>
  1141 <td class='script'>
  1142 <pre class='_interrupted_cline'>
  1143 \$ find / -name abc</pre>
  1144 <pre class='interrupted_output'>find: /home/devi-orig/.gnome2: Keine Berechtigung
  1145 find: /home/devi-orig/.gnome2_private: Keine Berechtigung
  1146 find: /home/devi-orig/.nautilus/metafiles: Keine Berechtigung
  1147 find: /home/devi-orig/.metacity: Keine Berechtigung
  1148 find: /home/devi-orig/.inkscape: Keine Berechtigung
  1149 ^C
  1150 </pre>
  1151 </td>
  1152 </tr>
  1153 </table>
  1154 <br/>
  1155     </p></li>
  1156     <li><p>
  1157     Команды, выполненные с привилегиями суперпользователя,
  1158     выделяются слева красной чертой.
  1159 <table>
  1160 <tr class='command'>
  1161 <td class='script'>
  1162 <pre class='_root_cline'>
  1163 # id</pre>
  1164 <pre class='_root_output'>
  1165 uid=0(root) gid=0(root) Gruppen=0(root)
  1166 </pre>
  1167 </td>
  1168 </tr>
  1169 </table>
  1170     <br/>
  1171     </p></li>
  1172     <li><p>
  1173     Изменения, внесённые в текстовый файл с помощью редактора, 
  1174     запоминаются и показываются в журнале в формате ed.
  1175     Строки, начинающиеся символом "<", удалены, а строки,
  1176     начинающиеся символом ">" -- добавлены.
  1177 <table>
  1178 <tr class='command'>
  1179 <td class='script'>
  1180 <pre class='cline'>
  1181 \$ vi ~/.bashrc</pre>
  1182 <table><tr><td width='5'/><td class='diff'><pre>2a3,5
  1183 >    if [ -f /usr/local/etc/bash_completion ]; then
  1184 >         . /usr/local/etc/bash_completion
  1185 >        fi
  1186 </pre></td></tr></table></td>
  1187 </tr>
  1188 </table>
  1189     <br/>
  1190     </p></li>
  1191     <li><p>
  1192     Для того чтобы изменить файл в соответствии с показанными в диффшоте
  1193     изменениями, можно воспользоваться командой patch.
  1194     Нужно скопировать изменения, запустить программу patch, указав в
  1195     качестве её аргумента файл, к которому применяются изменения,
  1196     и всавить скопированный текст:
  1197 <table>
  1198 <tr class='command'>
  1199 <td class='script'>
  1200 <pre class='cline'>
  1201 \$ patch ~/.bashrc</pre>
  1202 </td>
  1203 </tr>
  1204 </table>
  1205     В данном случае изменения применяются к файлу ~/.bashrc
  1206     </p></li>
  1207     <li><p>
  1208     Для того чтобы получить краткую справочную информацию о команде, 
  1209     нужно подвести к ней мышь. Во всплывающей подсказке появится краткое
  1210     описание команды.
  1211     </p>
  1212     <p>
  1213     Если справочная информация о команде есть, 
  1214     команда выделяется голубым фоном, например: <span class="with_hint" title="главный текстовый редактор Unix">vi</span>.
  1215     Если справочная информация отсутствует,
  1216     команда выделяется розовым фоном, например: <span class="without_hint">notepad.exe</span>.
  1217     Справочная информация может отсутствовать в том случае, 
  1218     если (1) команда введена неверно; (2) если распознавание команды LiLaLo выполнено неверно;
  1219     (3) если информация о команде неизвестна LiLaLo.
  1220     Последнее возможно для редких команд.
  1221     </p></li>
  1222     <li><p>
  1223     Большие, в особенности многострочные, всплывающие подсказки лучше 
  1224     всего показываются браузерами KDE Konqueror, Apple Safari и Microsoft Internet Explorer.
  1225     В браузерах Mozilla и Firefox они отображаются не полностью, 
  1226     а вместо перевода строки выводится специальный символ.
  1227     </p></li>
  1228     <li><p>
  1229     Время ввода команды, показанное в журнале, соответствует времени 
  1230     <i>начала ввода командной строки</i>, которое равно тому моменту, 
  1231     когда на терминале появилось приглашение интерпретатора
  1232     </p></li>
  1233     <li><p>
  1234     Имя терминала, на котором была введена команда, показано в специальном блоке.
  1235     Этот блок показывается только в том случае, если терминал
  1236     текущей команды отличается от терминала предыдущей.
  1237     </p></li>
  1238     <li><p>
  1239     Вывод не интересующих вас в настоящий момент элементов журнала,
  1240     таких как время, имя терминала и других, можно отключить.
  1241     Для этого нужно воспользоваться <a href='#visibility_form'>формой управления журналом</a>
  1242     вверху страницы.
  1243     </p></li>
  1244     <li><p>
  1245     Небольшие комментарии к командам можно вставлять прямо из командной строки.
  1246     Комментарий вводится прямо в командную строку, после символов #^ или #v.
  1247     Символы ^ и v показывают направление выбора команды, к которой относится комментарий:
  1248     ^ - к предыдущей, v - к следующей.
  1249     Например, если в командной строке было введено:
  1250 <pre class='cline'>
  1251 \$ whoami
  1252 </pre>
  1253 <pre class='output'>
  1254 user
  1255 </pre>
  1256 <pre class='cline'>
  1257 \$ #^ Интересно, кто я?
  1258 </pre>
  1259     в журнале это будет выглядеть так:
  1261 <pre class='cline'>
  1262 \$ whoami
  1263 </pre>
  1264 <pre class='output'>
  1265 user
  1266 </pre>
  1267 <table class='note'><tr><td width='100%' class='note_text'>
  1268 <tr> <td> Интересно, кто я?<br/> </td></tr></table> 
  1269     </p></li>
  1270     <li><p>
  1271     Если комментарий содержит несколько строк,
  1272     его можно вставить в журнал следующим образом:
  1273 <pre class='cline'>
  1274 \$ whoami
  1275 </pre>
  1276 <pre class='output'>
  1277 user
  1278 </pre>
  1279 <pre class='cline'>
  1280 \$ cat > /dev/null #^ Интересно, кто я?
  1281 </pre>
  1282 <pre class='output'>
  1283 Программа whoami выводит имя пользователя, под которым 
  1284 мы зарегистрировались в системе.
  1285 -
  1286 Она не может ответить на вопрос о нашем назначении 
  1287 в этом мире.
  1288 </pre>
  1289     В журнале это будет выглядеть так:
  1290 <table>
  1291 <tr class='command'>
  1292 <td class='script'>
  1293 <pre class='cline'>
  1294 \$ whoami</pre>
  1295 <pre class='output'>user
  1296 </pre>
  1297 <table class='note'><tr><td class='note_title'>Интересно, кто я?</td></tr><tr><td width='100%' class='note_text'>
  1298 Программа whoami выводит имя пользователя, под которым<br/>
  1299 мы зарегистрировались в системе.<br/>
  1300 <br/>
  1301 Она не может ответить на вопрос о нашем назначении<br/>
  1302 в этом мире.<br/>
  1303 </td></tr></table>
  1304 </td>
  1305 </tr>
  1306 </table>
  1307     Для разделения нескольких абзацев между собой
  1308     используйте символ "-", один в строке.
  1309     <br/>
  1310 </p></li>
  1311     <li><p>
  1312     Комментарии, не относящиеся непосредственно ни к какой из команд, 
  1313     добавляются точно таким же способом, только вместо симолов #^ или #v 
  1314     нужно использовать символы #=
  1315     </p></li>
  1316 </ol>
  1317 HELP
  1319 $Html_About = <<ABOUT;
  1320     <p>
  1321     LiLaLo (L3) расшифровывается как Live Lab Log.<br/>
  1322     Программа разработана для повышения эффективности обучения Unix/Linux-системам.<br/>
  1323     (c) Игорь Чубин, 2004-2006<br/>
  1324     </p>
  1325 ABOUT
  1326 $Html_About.='$Id$ </p>';
  1328 $Html_JavaScript = <<JS;
  1329     function getElementsByClassName(Class_Name)
  1330     {
  1331         var Result=new Array();
  1332         var All_Elements=document.all || document.getElementsByTagName('*');
  1333         for (i=0; i<All_Elements.length; i++)
  1334             if (All_Elements[i].className==Class_Name)
  1335         Result.push(All_Elements[i]);
  1336         return Result;
  1337     }
  1338     function ShowHide (name)
  1339     {
  1340         elements=getElementsByClassName(name);
  1341         for(i=0; i<elements.length; i++)
  1342             if (elements[i].style.display == "none")
  1343                 elements[i].style.display = "";
  1344             else
  1345                 elements[i].style.display = "none";
  1346             //if (elements[i].style.visibility == "hidden")
  1347             //  elements[i].style.visibility = "visible";
  1348             //else
  1349             //  elements[i].style.visibility = "hidden";
  1350     }
  1351     function filter_by_output(text)
  1352     {
  1354         var jjj=0;
  1356         elements=getElementsByClassName('command');
  1357         for(i=0; i<elements.length; i++) {
  1358             subelems = elements[i].getElementsByTagName('pre');
  1359             for(j=0; j<subelems.length; j++) {
  1360                 if (subelems[j].className = 'output') {
  1361                     var str = new String(subelems[j].nodeValue);
  1362                     if (jjj != 1) { 
  1363                         alert(str);
  1364                         jjj=1;
  1365                     }
  1366                     if (str.indexOf(text) >0) 
  1367                         subelems[j].style.display = "none";
  1368                     else
  1369                         subelems[j].style.display = "";
  1371                 }
  1373             }
  1374         }       
  1376     }
  1377 JS
  1379 %Search_Machines = (
  1380         "google" =>     {   "query" =>  "http://www.google.com/search?q=" ,
  1381                     "icon"  =>  "$Config{frontend_google_ico}" },
  1382         "freebsd" =>    {   "query" =>  "http://www.freebsd.org/cgi/man.cgi?query=",
  1383                     "icon"  =>  "$Config{frontend_freebsd_ico}" },
  1384         "linux"  =>     {   "query" =>  "http://man.he.net/?topic=",
  1385                     "icon"  =>  "$Config{frontend_linux_ico}"},
  1386         "opennet"  =>   {   "query" =>  "http://www.opennet.ru/search.shtml?words=",
  1387                     "icon"  =>  "$Config{frontend_opennet_ico}"},
  1388         "local" =>  {   "query" =>  "http://www.freebsd.org/cgi/man.cgi?query=",
  1389                     "icon"  =>  "$Config{frontend_local_ico}" },
  1391     );
  1393 %Elements_Visibility = (
  1394         "0 new_commands_table"      =>  "новые команды",
  1395         "1 diff"      =>  "редактор",
  1396         "2 time"      =>  "время",
  1397         "3 ttychange"     =>  "терминал",
  1398         "4 wrong_output wrong_cline wrong_root_output wrong_root_cline" 
  1399                 =>  "команды с ненулевым кодом завершения",
  1400         "5 mistyped_output mistyped_cline mistyped_root_output mistyped_root_cline" 
  1401                 =>  "неверно набранные команды",
  1402         "6 interrupted_output interrupted_cline interrupted_root_output interrupted_root_cline" 
  1403                 =>  "прерванные команды",
  1404         "7 tab_completion_output tab_completion_cline"    
  1405                 =>  "продолжение с помощью tab"
  1406 );
  1408 @Day_Name      = qw/ Воскресенье Понедельник Вторник Среда Четверг Пятница Суббота /;
  1409 @Month_Name    = qw/ Январь Февраль Март Апрель Май Июнь Июль Август Сентябрь Октябрь Ноябрь Декабрь /;
  1410 @Of_Month_Name = qw/ Января Февраля Марта Апреля Мая Июня Июля Августа Сентября Октября Ноября Декабря /;
  1411 }
  1416 # Временно удалённый код
  1417 # Возможно, он не понадобится уже никогда
  1420 sub search_by
  1421 {
  1422     my $sm = shift;
  1423     my $topic = shift;
  1424     $topic =~ s/ /+/;
  1426     return "<a href='". $Search_Machines{$sm}->{"query"}."$topic'><img width='16' height='16' src='".
  1427                 $Search_Machines{$sm}->{"icon"}."' border='0'/></a>";
  1428 }
