lilalo
view l3-frontend @ 80:d28dda8ea18f
1)
Изменён формат имени diff-файлов.
Теперь в имени присутствует только название сессии, время и имя файла.
2)
Можно просмотреть отдельную сессию.
Для этого нужно щёлкнуть по блоку сессии в журнале
3)
Исправлена ошибка с таблицей новых команд в последнем дне.
Раньше она просто не показывалась
4)
Запись lablog-ов теперь ведётся только для интерактивных shell'ов
Неинтерактивные работают как обычно.
Изменён формат имени diff-файлов.
Теперь в имени присутствует только название сессии, время и имя файла.
2)
Можно просмотреть отдельную сессию.
Для этого нужно щёлкнуть по блоку сессии в журнале
3)
Исправлена ошибка с таблицей новых команд в последнем дне.
Раньше она просто не показывалась
4)
Запись lablog-ов теперь ведётся только для интерактивных shell'ов
Неинтерактивные работают как обычно.
| author | devi | 
|---|---|
| date | Mon Feb 20 17:52:40 2006 +0200 (2006-02-20) | 
| parents | 58ea78973bbb | 
| children | d9a700d48bef | 
 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_session="";
   398     my $last_day=q();
   399     my $last_wday=q();
   400     my $in_range=0;
   402     my $current_command=0;
   404     my @known_commands;
   406     my %filter;
   408     if ($Config{filter}) {
   409         # Инициализация фильтра
   410         for (split /&/,$Config{filter}) {
   411             my ($var, $val) = split /=/;
   412             $filter{$var} = $val || "";
   413         }
   414     }
   416     #$result = "Filter=".$Config{filter}."\n";
   418     $Stat{LastCommand}   ||= 0;
   419     $Stat{TotalCommands} ||= 0;
   420     $Stat{ErrorCommands} ||= 0;
   421     $Stat{MistypedCommands} ||= 0;
   423     my %new_entries_of = (
   424         "1 1"     =>   "программы пользователя",
   425         "2 8"     =>   "программы администратора",
   426         "3 sh"    =>   "команды интерпретатора",
   427         "4 script"=>   "скрипты",
   428     );
   430 COMMAND_LINE:
   431     for my $k (@Command_Lines_Index) {
   433         my $cl=$Command_Lines[$Command_Lines_Index[$current_command++]];
   434         next unless $cl;
   436 # Пропускаем команды, с одинаковым временем
   437 # Это не совсем правильно.
   438 # Возможно, что это команды, набираемые с помощью <completion>
   439 # или запомненные с помощью <ctrl-c>
   441         next if $Stat{LastCommand} == $cl->{time};
   443 # Пропускаем строки, которые противоречат фильтру
   444 # Если у нас недостаточно информации о том, подходит строка под  фильтр или нет, 
   445 # мы её выводим
   447         #$result .= "before<br/>";
   448         for my $filter_key (keys %filter) {
   449             #$result .= "undefined local session id<br/>\n" if !defined($cl->{local_session_id});
   450             #$result .= "undefined filter key $filter_key <br/>\n" if !defined($Sessions{$cl->{local_session_id}}->{$filter_key});
   451             #$result .= $Sessions{$cl->{local_session_id}}->{$filter_key}." != ".$filter{$filter_key};
   452             next COMMAND_LINE if 
   453                 defined($cl->{local_session_id}) 
   454                 && defined($Sessions{$cl->{local_session_id}}->{$filter_key}) 
   455                 && $Sessions{$cl->{local_session_id}}->{$filter_key} ne $filter{$filter_key};
   456         }
   458 # Набираем статистику
   459 # Хэш %Stat
   461         $Stat{FirstCommand} = $cl->{time} unless $Stat{FirstCommand};
   462         if ($cl->{time} - $Stat{LastCommand} < $Config{stat_inactivity_interval}) {
   463             $Stat{TotalTime} += $cl->{time} - $Stat{LastCommand}
   464         }
   465         my $seconds_since_last_command = $cl->{time} - $Stat{LastCommand};
   466         $Stat{LastCommand} = $cl->{time};
   467         $Stat{TotalCommands}++;
   470 # Пропускаем строки, выходящие за границу "signature",
   471 # при условии, что границы указаны
   472 # Пропускаем неправильные/прерванные/другие команды
   473         if ($Config{"from"} && $cl->{"cline"} =~ /$Config{"signature"}\s*$Config{"from"}/) {
   474             $in_range=1;
   475             next;
   476         }
   477         if ($Config{"to"} && $cl->{"cline"} =~ /$Config{"signature"}\s*$Config{"to"}/) {
   478             $in_range=0;
   479             next;
   480         }
   481         next    if ($Config{"from"} && $Config{"to"}   && !$in_range) 
   482                 || ($Config{"skip_empty"} =~ /^y/i     && $cl->{"cline"} =~ /^\s*$/ )
   483                 || ($Config{"skip_wrong"} =~ /^y/i     && $cl->{"err"} != 0)
   484                 || ($Config{"skip_interrupted"} =~ /^y/i && $cl->{"err"} == 130);
   486         if ($cl->{class} eq "note") {
   487             my $note = $cl->{note};
   488             $note = join ("\n", map ("<p>$_</p>", split (/-\n/, $note)));
   489             $note =~ s@(http:[a-zA-Z.0-9/?\_%-]*)@<a href='$1'>$1</a>@g;
   490             $note =~ s@(www\.[a-zA-Z.0-9/?\_%-]*)@<a href='$1'>$1</a>@g;
   491             $this_day_result .= "<tr><td colspan='6'>"
   492                              .  "<h4 id='note$note_number'>".$cl->{note_title}."</h4>" if $cl->{note_title}
   493                              .  "".$note."<p/><p/></td></tr>";
   495             if ($cl->{note_title}) {
   496                 push @{$toc[@toc]},"<a href='#note$note_number'>".$cl->{note_title}."</a>";
   497                 $note_number++;
   498             }
   499             next;
   500         }
   503         my $output="";
   504 # Выводим <head_lines> верхних строк
   505 # и <tail_lines> нижних строк,
   506 # если эти параметры существуют
   508         if ($cl->{"last_command"} eq "cat" && !$cl->{"err"} && !($cl->{"cline"} =~ /</)) {
   509             my $filename = $cl->{"cline"};
   510             $filename =~ s/.*\s+(\S+)\s*$/$1/;
   511             $Files{$filename}->{"content"} = $cl->{"output"};
   512             $Files{$filename}->{"source_command_id"} = $cl->{"id"}
   513         }
   514         my @lines = split '\n', $cl->{"output"};
   515         if ((
   516              $Config{"head_lines"} 
   517              || $Config{"tail_lines"}
   518              )
   519              && $#lines >  $Config{"head_lines"} + $Config{"tail_lines"} ) {
   521             for (my $i=0; $i<= $#lines && $i < $Config{"head_lines"}; $i++) {
   522                 $output .= $lines[$i]."\n";
   523             }
   524             $output .= $Config{"skip_text"}."\n";
   526             my $start_line=$#lines-$Config{"tail_lines"}+1;
   527             for ($i=$start_line; $i<= $#lines; $i++) {
   528                 $output .= $lines[$i]."\n";
   529             }
   530         } 
   531         else {
   532            $ output .= $cl->{"output"};
   533         }   
   535 #
   536 ##
   537 ## Начинается собственно вывод
   538 ##
   539 #
   541         my ($sec,$min,$hour,$day,$mon,$year,$wday,$yday,$isdst) = localtime($cl->{time});
   543         # Добавляем спереди 0 для удобочитаемости
   544         $min  = "0".$min  if $min  =~ /^.$/;
   545         $hour = "0".$hour if $hour =~ /^.$/;
   546         $sec  = "0".$sec  if $sec  =~ /^.$/;
   548         $class=$cl->{"class"};
   549         $Stat{ErrorCommands}++          if $class =~ /wrong/;
   550         $Stat{MistypedCommands}++       if $class =~ /mistype/;
   553 # DAY CHANGE
   554         if ( $last_day ne $day) {
   555             if ($last_day) {
   557 # Вычисляем разность множеств.
   558 # Что-то вроде этого, если бы так можно было писать:
   559 #   @new_commands = keys %CommandsFDistribution - @known_commands;
   562                 $result .= "<h3 id='day$last_day'>".$Day_Name[$last_wday]."</h3>";
   566                 for my $entry_class (sort keys %new_entries_of) {
   567                     my $new_commands_section = make_new_entries_table($entry_class=~/[0-9]+\s+(.*)/, \@known_commands);
   569                     my $table_caption = "Таблица "
   570                                       . $table_number++
   571                                       . ". "
   572                                       . $Day_Name[$last_wday]
   573                                       . ". Новые "
   574                                       . $new_entries_of{$entry_class};
   575                     if ($new_commands_section) {
   576                         $result .= "<table class='new_commands_table' width='700' cellspacing='0' cellpadding='0'>"
   577                                 .  "<tr class='new_commands_caption'>"
   578                                 .  "<td colspan='2' align='right'>$table_caption</td>"
   579                                 .  "</tr>"
   580                                 .  "<tr class='new_commands_header'>"
   581                                 .  "<td width=100>Команда</td><td width=600>Описание</td>"
   582                                 .  "</tr>"
   583                                 .  $new_commands_section 
   584                                 .  "</table>"
   585                     }
   587                 }
   588                 @known_commands = keys %CommandsFDistribution;
   589                 #$result .= "<table width='100%'>\n";
   590                 $result .= $this_day_result;
   591                 #$result .= "</table>";
   592             }
   594             push @toc, "<a href='#day$day'>".$Day_Name[$wday]."</a>\n";
   595             $last_day=$day;
   596             $last_wday=$wday;
   597             $this_day_result = q();
   598         }
   599         elsif ($seconds_since_last_command > 7200) {
   600             my $hours_passed =  int($seconds_since_last_command/3600);
   601             my $passed_word  = $minutes_passed % 10 == 1 ? "прошла"
   602                                                          : "прошло";
   603             my $hours_word   = $hours_passed % 10 == 1 ?   "часа":
   604                                                            "часов";
   605             $this_day_result .= "<div class='much_time_passed'>"
   606                              .  $passed_word." >".$hours_passed." ".$hours_word
   607                              .  "</div>\n";
   608         }
   609         elsif ($seconds_since_last_command > 600) {
   610             my $minutes_passed =  int($seconds_since_last_command/60);
   613             my $passed_word  = $minutes_passed % 100 > 10 
   614                             && $minutes_passed % 100 < 20 ? "прошло"
   615                              : $minutes_passed % 10 == 1  ? "прошла"
   616                                                           : "прошло";
   618             my $minutes_word = $minutes_passed % 100 > 10 
   619                             && $minutes_passed % 100 < 20 ? "минут" :
   620                                $minutes_passed % 10 == 1 ? "минута":
   621                                $minutes_passed % 10 == 0 ? "минут" :
   622                                $minutes_passed % 10  > 4 ? "минут" :
   623                                                            "минуты";
   625             if ($seconds_since_last_command < 1800) {
   626             $this_day_result .= "<div class='time_passed'>"
   627                              .  $passed_word." ".$minutes_passed." ".$minutes_word
   628                              .  "</div>\n";
   629             }
   630             else {
   631             $this_day_result .= "<div class='much_time_passed'>"
   632                              .  $passed_word." ".$minutes_passed." ".$minutes_word
   633                              .  "</div>\n";
   634             }
   635         }
   637         #$this_day_result .= "<table cellspacing='0' cellpading='0' class='command' id='command:".$cl->{"id"}."' width='100%'><tr>\n";
   638         $this_day_result .= "<div class='command' id='command:".$cl->{"id"}."' >\n";
   641 # CONSOLE CHANGE
   642         if ( $last_tty ne $cl->{"tty"} && 0) {
   643             my $tty = $cl->{"tty"};
   644             $this_day_result .= "<div class='ttychange'>"
   645                                 . $tty
   646                                 ."</div>";
   647             $last_tty=$cl->{"tty"};
   648         }
   650 # Session change
   651         if ( $last_session ne $cl->{"local_session_id"}) {
   652             my $tty = $cl->{"tty"};
   653             $this_day_result .= "<a href='?local_session_id=".$cl->{"local_session_id"}."'><div class='ttychange'>"
   654                                 . $Sessions{$cl->{"local_session_id"}}->{"tty"}
   655                                 ."</div></a>";
   656             $last_session=$cl->{"local_session_id"};
   657         }
   659 # TIME
   660         $this_day_result .= "<div class='time'>$hour:$min:$sec</div>" 
   661                             if $Config{"show_time"} =~ /^y/i;
   663         #$this_day_result .= $Config{"show_time"} =~ /^y/i
   664         #         ? "<td width='100' valign='top' class='time' width='$Config{time_width}'>$hour:$min:$sec</td>"
   665         #         : "<td width='0'/>";
   667 # CLASS
   668 #        if ($cl->{"err"}) {
   669 #            $this_day_result .= "<td width='6' valign='top'>"
   670 #                             .  "<table><tr><td width='6' height='6' class='err_box'>"
   671 #                             .  "E"
   672 #                             .  "</td></tr></table>"
   673 #                             .  "</td>";
   674 #        }
   675 #        else {
   676 #            $this_day_result .= "<td width='10' valign='top'>"
   677 #                             .  " "
   678 #                             .  "</td>";
   679 #        }
   681 # COMMAND
   682         my $hint = make_comment($cl->{"cline"});
   684         my $cline;
   685         $cline = $cl->{"prompt"}.$cl->{"cline"};
   686         $cline =~ s/\n//;
   688         $cline = "<span title='$hint' class='with_hint'>$cline</span>" if $hint;
   689         $cline = "<span class='without_hint'>$cline</span>" if !$hint;
   691         $this_day_result .= "<table cellpadding='0' cellspacing='0'><tr><td>\n<div class='cblock_$cl->{class}'>\n";
   692         $this_day_result .= "<div class='cline'>\n" . $cline ;      #cline
   693         $this_day_result .= "<span title='Код завершения ".$cl->{"err"}."'>\n"
   694                          .  "<img src='".$Config{frontend_ico_path}."/error.png'/>\n"
   695                          .  "</span>\n" if $cl->{"err"};
   696         $this_day_result .= "</div>\n";                             #cline
   698 # OUTPUT
   699         my $last_command = $cl->{"last_command"};
   700         if (!( 
   701         $Config{"suppress_editors"} =~ /^y/i && grep ($_ eq $last_command, @{$Config{"editors"}}) ||
   702         $Config{"suppress_pagers"}  =~ /^y/i && grep ($_ eq $last_command, @{$Config{"pagers"}}) ||
   703         $Config{"suppress_terminal"}=~ /^y/i && grep ($_ eq $last_command, @{$Config{"terminal"}})
   704             )) {
   705             $this_day_result .= "<pre class='output'>\n" . $output . "</pre>\n";
   706         }   
   708 # DIFF
   709         $this_day_result .= "<pre class='diff'>".$cl->{"diff"}."</pre>"
   710             if ( $Config{"show_diffs"} =~ /^y/i && $cl->{"diff"});
   712 #NOTES
   713         if ( $Config{"show_notes"} =~ /^y/i && $cl->{"note"}) {
   714             my $note=$cl->{"note"};
   715             $note =~ s/\n/<br\/>\n/msg;
   716             if (not $note =~ s@(http:[a-zA-Z.0-9/_?%-]*)@<a href='$1'>$1</a>@g) {
   717               $note =~ s@(www\.[a-zA-Z.0-9/_?%-]*)@<a href='$1'>$1</a>@g;
   718             };
   719             $this_day_result .= "<div class='note'>";
   720             $this_day_result .= "<div class='note_title'>".$cl->{note_title}."</div>" if $cl->{note_title};
   721             $this_day_result .= "<div class='note_text'>".$note."</div>";
   722             $this_day_result .= "</div>\n";
   723         }
   725 # COMMENT
   726         if ( $Config{"show_comments"} =~ /^y/i) {
   727             my $comment = make_comment($cl->{"cline"});
   728             if ($comment) {
   729                 $this_day_result .= 
   730                            "<div class='note' width='100%'>"
   731                         .  $comment
   732                         .  "</div>\n"
   733                         ;
   735             }
   736         }
   738         # Вывод очередной команды окончен
   739         $this_day_result .= "</div>\n";                     # cblock
   740         $this_day_result .= "</td></tr></table>\n"
   741                          .  "</div>\n";                     # command
   742     }
   743     last: {
   744         $result .= "<h3 id='day$last_day'>".$Day_Name[$last_wday]."</h3>";
   746         for my $entry_class (keys %new_entries_of) {
   747             my $new_commands_section = make_new_entries_table($entry_class=~/[0-9]+\s+(.*)/, \@known_commands);
   748             my $table_caption = "Таблица "
   749                                 . $table_number++
   750                                 . ". "
   751                                 . $Day_Name[$last_wday]
   752                                 . ". Новые "
   753                                 . $new_entries_of{$entry_class};
   754             if ($new_commands_section) {
   755                 $result .= "<table class='new_commands_table' width='700' cellspacing='0' cellpadding='0'>"
   756                         .  "<tr class='new_commands_caption'>"
   757                         .  "<td colspan='2' align='right'>$table_caption</td>"
   758                         .  "</tr>"
   759                         .  "<tr class='new_commands_header'>"
   760                         .  "<td width=100>Команда</td><td width=600>Описание</td>"
   761                         .  "</tr>"
   762                         .  $new_commands_section 
   763                         .  "</table>"
   764             }
   766         }
   767         @known_commands = keys %CommandsFDistribution;
   769         $result .= $this_day_result;
   770    }
   772     return ($result, collapse_list (\@toc));
   774 }
   776 sub make_new_entries_table
   777 {
   778     my $entries_class = shift;
   779     my @known_commands = @{$_[0]};
   781     my %count;
   782     my @new_commands = ();
   783     for my $c (keys %CommandsFDistribution, @known_commands) {
   784         $count{$c}++
   785     }
   786     for my $c (keys %CommandsFDistribution) {
   787         push @new_commands, $c if $count{$c} != 2;
   788     }
   791     my $new_commands_section;
   792     if (@new_commands){
   793         my $hint;
   794         for my $c (reverse sort { $CommandsFDistribution{$a} <=> $CommandsFDistribution{$b} } @new_commands) {
   795                 $hint = make_comment($c);
   796                 next unless $hint;
   797                 my ($command, $hint) = $hint =~ m/(.*?) \s*- \s*(.*)/;
   798                 next unless $command =~ s/\($entries_class\)//i;
   799                 $new_commands_section .= "<tr><td valign='top'>$command</td><td>$hint</td></tr>";
   800         }
   801     }
   802     return $new_commands_section;
   803 }
   806 #############
   807 # print_all
   808 #
   809 #
   810 #
   811 # In:       $_[0]       output_filename
   812 # Out:
   815 sub print_all
   816 {
   817     my $output_filename=$_[0];
   819     my $result;
   820     my ($command_lines,$toc)  = print_command_lines;
   821     my $files_section         = print_files;
   823     $result = print_header($toc);
   824     $result.= "<h2 id='log'>Журнал</h2>"       . $command_lines;
   825     $result.= "<h2 id='files'>Файлы</h2>"      . $files_section if $files_section;
   826     $result.= "<h2 id='stat'>Статистика</h2>"  . print_stat;
   827     $result.= "<h2 id='help'>Справка</h2>"     . $Html_Help . "<br/>"; 
   828     $result.= "<h2 id='about'>О программе</h2>". $Html_About. "<br/>"; 
   829     $result.= print_footer;
   831     if ($output_filename eq "-") {
   832         print $result;
   833     }
   834     else {
   835         open(OUT, ">", $output_filename)
   836             or die "Can't open $output_filename for writing\n";
   837         print OUT $result;
   838         close(OUT);
   839     }
   840 }
   842 #############
   843 # print_header
   844 #
   845 #
   846 #
   847 # In:   $_[0]       Содержание
   848 # Out:              Распечатанный заголовок
   850 sub print_header
   851 {
   852     my $toc = $_[0];
   853     my $course_name = $Config{"course-name"};
   854     my $course_code = $Config{"course-code"};
   855     my $course_date = $Config{"course-date"};
   856     my $course_center = $Config{"course-center"};
   857     my $course_trainer = $Config{"course-trainer"};
   858     my $course_student = $Config{"course-student"};
   860     my $title    = "Журнал лабораторных работ";
   861     $title      .= " -- ".$course_student if $course_student;
   862     if ($course_date) {
   863         $title  .= " -- ".$course_date; 
   864         $title  .= $course_code ? "/".$course_code 
   865                                 : "";
   866     }
   867     else {
   868         $title  .= " -- ".$course_code if $course_code;
   869     }
   871     # Управляющая форма
   872     my $control_form .= "<div class='visibility_form' title='Выберите какие элементы должны быть показаны в журнале'>"
   873                      .  "<span class='header'>Видимые элементы</span>"
   874                      .  "<span class='window_controls'><a href='' onclick='' title='свернуть форму управления'>_</a> <a href='' onclick='' title='закрыть форму управления'>x</a></span>"
   875                      .  "<div><form>\n";
   876     for my $element (sort keys %Elements_Visibility)
   877     {
   878         my ($skip, @e) = split /\s+/, $element;
   879         my $showhide = join "", map { "ShowHide('$_');" } @e ;
   880         $control_form .= "<div><input type='checkbox' name='$e[0]' onclick=\"$showhide\" checked>".
   881                 $Elements_Visibility{$element}.
   882                 "</input></div>";
   883     }
   884     $control_form .= "</form>\n"
   885                   .  "</div>\n";
   887     my $result;
   888     $result = <<HEADER;
   889     <html>
   890     <head>
   891     <meta content='text/html; charset=utf-8' http-equiv='Content-Type' />
   892     <link rel='stylesheet' href='$Config{frontend_css}' type='text/css'/>
   893     <title>$title</title>
   894     </head>
   895     <body>
   896     <script>
   897     $Html_JavaScript
   898     </script>
   900 <!-- vvv Tigra Hints vvv -->
   901 <script language="JavaScript" src="/tigra/hints.js"></script>
   902 <script language="JavaScript" src="/tigra/hints_cfg.js"></script>
   903 <style>
   904 /* a class for all Tigra Hints boxes, TD object */
   905     .hintsClass
   906         {text-align: center; font-family: Verdana, Arial, Helvetica; padding: 0px 0px 0px 0px;}
   907 /* this class is used by Tigra Hints wrappers */
   908     .row
   909         {background: white;}
   910 </style>
   911 <!-- ^^^ Tigra Hints ^^^ -->
   914     <h1 onmouseover="myHint.show('1')" onmouseout="myHint.hide()">Журнал лабораторных работ</h1>
   915 HEADER
   916     if (    $course_student 
   917             || $course_trainer 
   918             || $course_name 
   919             || $course_code 
   920             || $course_date 
   921             || $course_center) {
   922             $result .= "<p>";
   923             $result .= "Выполнил $course_student<br/>"  if $course_student;
   924             $result .= "Проверил $course_trainer <br/>" if $course_trainer;
   925             $result .= "Курс "                          if $course_name 
   926                                                             || $course_code 
   927                                                             || $course_date;
   928             $result .= "$course_name "                  if $course_name;
   929             $result .= "($course_code)"                 if $course_code;
   930             $result .= ", $course_date<br/>"            if $course_date;
   931             $result .= "Учебный центр $course_center <br/>" if $course_center;
   932             $result .= "</p>";
   933     }
   935     $result .= <<HEADER;
   936     <table width='100%'>
   937     <tr>
   938     <td width='*'>
   940     <table border=0 id='toc' class='toc'>
   941     <tr>
   942     <td>
   943     <div class='toc_title'>Содержание</div>
   944     <ul>
   945         <li><a href='#log'>Журнал</a></li>
   946         <ul>$toc</ul>
   947         <li><a href='#files'>Файлы</a></li>
   948         <li><a href='#stat'>Статистика</a></li>
   949         <li><a href='#help'>Справка</a></li>
   950         <li><a href='#about'>О программе</a></li>
   951     </ul>
   952     </td>
   953     </tr>
   954     </table>
   956     </td>
   957     <td valign='top' width=200>$control_form</td>
   958     </tr>
   959     </table>
   960 HEADER
   962     return $result;
   963 }
   966 #############
   967 # print_footer
   968 #
   969 #
   970 #
   971 #
   972 #
   974 sub print_footer
   975 {
   976     return "</body>\n</html>\n";
   977 }
   982 #############
   983 # print_stat
   984 #
   985 #
   986 #
   987 # In:
   988 # Out:
   990 sub print_stat
   991 {
   992     %StatNames = (
   993         FirstCommand        => "Время первой команды журнала",
   994         LastCommand         => "Время последней команды журнала",
   995         TotalCommands       => "Количество командных строк в журнале",
   996         ErrorsPercentage    => "Процент команд с ненулевым кодом завершения, %",
   997         MistypesPercentage  => "Процент синтаксически неверно набранных команд, %",
   998         TotalTime           => "Суммарное время работы с терминалом <sup><font size='-2'>*</font></sup>, час",
   999         CommandsPerTime     => "Количество командных строк в единицу времени, команда/мин",
  1000         CommandsFrequency   => "Частота использования команд",
  1001         RareCommands        => "Частота использования этих команд < 0.5%",
  1002     );
  1003     @StatOrder = (
  1004         FirstCommand,
  1005         LastCommand,
  1006         TotalCommands,
  1007         ErrorsPercentage,
  1008         MistypesPercentage,
  1009         TotalTime,
  1010         CommandsPerTime,
  1011         CommandsFrequency,
  1012         RareCommands,
  1013     );
  1015     # Подготовка статистики к выводу
  1016     # Некоторые значения пересчитываются!
  1017     # Дальше их лучше уже не использовать!!!
  1019     my %CommandsFrequency = %CommandsFDistribution;
  1021     $Stat{TotalTime} ||= 0;
  1022     my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($Stat{FirstCommand} || 0);
  1023     $Stat{FirstCommand} = sprintf "%02i:%02i:%02i %04i-%2i-%2i", $hour, $min, $sec,  $year+1900, $mon+1, $mday;
  1024     ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($Stat{LastCommand} || 0);
  1025     $Stat{LastCommand} = sprintf "%02i:%02i:%02i %04i-%2i-%2i", $hour, $min, $sec,  $year+1900, $mon+1, $mday;
  1026     if ($Stat{TotalCommands}) {
  1027         $Stat{ErrorsPercentage} = sprintf "%5.2f", $Stat{ErrorCommands}*100/$Stat{TotalCommands};
  1028         $Stat{MistypesPercentage} = sprintf "%5.2f", $Stat{MistypedCommands}*100/$Stat{TotalCommands};
  1029     }
  1030     $Stat{CommandsPerTime} = sprintf "%5.2f", $Stat{TotalCommands}*60/$Stat{TotalTime}
  1031         if $Stat{TotalTime};
  1032     $Stat{TotalTime} = sprintf "%5.2f", $Stat{TotalTime}/60/60;
  1034     my $total_commands=0;
  1035     for $command (keys %CommandsFrequency){
  1036         $total_commands += $CommandsFrequency{$command};
  1037     }
  1038     if ($total_commands) {
  1039         for $command (reverse sort {$CommandsFrequency{$a} <=> $CommandsFrequency{$b}} keys %CommandsFrequency){
  1040             my $command_html;
  1041             my $percentage = sprintf "%5.2f",$CommandsFrequency{$command}*100/$total_commands;
  1042             if ($percentage < 0.5) {
  1043                 my $hint = make_comment($command);
  1044                 $command_html = "$command";
  1045                 $command_html = "<span title='$hint' class='with_hint'>$command_html</span>" if $hint;
  1046                 $command_html = "<span class='without_hint'>$command_html</span>" if not $hint;
  1047                 my $command_html = "<tt>$command_html</tt>";
  1048                 $Stat{RareCommands} .= $command_html."<sub><font size='-2'>".$CommandsFrequency{$command}."</font></sub> , ";
  1049             }
  1050             else {
  1051                 my $hint = make_comment($command);
  1052                 $command_html = "$command";
  1053                 $command_html = "<span title='$hint' class='with_hint'>$command_html</span>" if $hint;
  1054                 $command_html = "<span class='without_hint'>$command_html</span>" if not $hint;
  1055                 my $command_html = "<tt>$command_html</tt>";
  1056                 $percentage = sprintf "%5.2f",$percentage;
  1057                 $Stat{CommandsFrequency} .= "<tr><td>".$command_html."</td><td>".$CommandsFrequency{$command}."</td>".
  1058                     "<td>|".("="x int($CommandsFrequency{$command}*100/$total_commands))."| $percentage%</td></tr>";
  1059             }
  1060         }
  1061         $Stat{CommandsFrequency} = "<table>".$Stat{CommandsFrequency}."</table>";
  1062         $Stat{RareCommands} =~ s/, $// if $Stat{RareCommands};
  1063     }
  1065     my $result = q();
  1066     for my $stat (@StatOrder) {
  1067         next unless $Stat{"$stat"};
  1068         $result .= "<tr valign='top'><td width='300'>".$StatNames{"$stat"}."</td><td>".$Stat{"$stat"}."</td></tr>"
  1069     }
  1070     $result  = "<table>$result</table>"
  1071              . "<font size='-2'>____<br/>*) Интервалы неактивности длительностью "
  1072              .  ($Config{stat_inactivity_interval}/60)
  1073              . " минут и более не учитываются</font></br>";
  1075     return $result;
  1076 }
  1079 sub collapse_list($)
  1080 {
  1081     my $res = "";
  1082     for my $elem (@{$_[0]}) {
  1083         if (ref $elem eq "ARRAY") {
  1084             $res .= "<ul>".collapse_list($elem)."</ul>";
  1085         }
  1086         else
  1087         {
  1088             $res .= "<li>".$elem."</li>";
  1089         }
  1090     }
  1091     return $res;
  1092 }
  1095 sub print_files
  1096 {
  1097     my $result = qq(); 
  1098     my @toc;
  1099     for my $file (sort keys %Files) {
  1100           my $div_id = "file:$file";
  1101           $div_id =~ s@/@_@g;
  1102           push @toc, "<a href='#$div_id'>$file</a>";
  1103           $result .= "<div class='filename' id='$div_id'>".$file."</div>\n"
  1104                   .  "<div class='file_navigation'><a href='#command:".$Files{$file}->{source_command_id}."'>".">"."</a></div>"
  1105                   .  "<div class='filedata'><pre>".$Files{$file}->{content}."</pre></div>";
  1106     }
  1107     return "<div class='files_toc'>".collapse_list(\@toc)."</div>".$result;
  1108 }
  1111 sub init_variables
  1112 {
  1113 $Html_Help = <<HELP;
  1114     Для того чтобы использовать LiLaLo, не нужно знать ничего особенного:
  1115     всё происходит само собой.
  1116     Однако, чтобы ведение и последующее использование журналов
  1117     было как можно более эффективным, желательно иметь в виду следующее:
  1118     <ol>
  1119     <li><p> 
  1120     В журнал автоматически попадают все команды, данные в любом терминале системы.
  1121     </p></li>
  1122     <li><p>
  1123     Для того чтобы убедиться, что журнал на текущем терминале ведётся, 
  1124     и команды записываются, дайте команду w.
  1125     В поле WHAT, соответствующем текущему терминалу, 
  1126     должна быть указана программа script.
  1127     </p></li>
  1128     <li><p>
  1129     Команды, при наборе которых были допущены синтаксические ошибки, 
  1130     выводятся перечёркнутым текстом:
  1131 <table>
  1132 <tr class='command'>
  1133 <td class='script'>
  1134 <pre class='_mistyped_cline'>
  1135 \$ l s-l</pre>
  1136 <pre class='_mistyped_output'>bash: l: command not found
  1137 </pre>
  1138 </td>
  1139 </tr>
  1140 </table>
  1141 <br/>
  1142     </p></li>
  1143     <li><p>
  1144     Если код завершения команды равен нулю, 
  1145     команда была выполнена без ошибок.
  1146     Команды, код завершения которых отличен от нуля, выделяются цветом.
  1147 <table>
  1148 <tr class='command'>
  1149 <td class='script'>
  1150 <pre class='_wrong_cline'>
  1151 \$ test 5 -lt 4</pre>
  1152 </pre>
  1153 </td>
  1154 </tr>
  1155 </table>
  1156     Обратите внимание на то, что код завершения команды может быть отличен от нуля
  1157     не только в тех случаях, когда команда была выполнена с ошибкой.
  1158     Многие команды используют код завершения, например, для того чтобы показать результаты проверки
  1159 <br/>
  1160     </p></li>
  1161     <li><p>
  1162     Команды, ход выполнения которых был прерван пользователем, выделяются цветом.
  1163 <table>
  1164 <tr class='command'>
  1165 <td class='script'>
  1166 <pre class='_interrupted_cline'>
  1167 \$ find / -name abc</pre>
  1168 <pre class='interrupted_output'>find: /home/devi-orig/.gnome2: Keine Berechtigung
  1169 find: /home/devi-orig/.gnome2_private: Keine Berechtigung
  1170 find: /home/devi-orig/.nautilus/metafiles: Keine Berechtigung
  1171 find: /home/devi-orig/.metacity: Keine Berechtigung
  1172 find: /home/devi-orig/.inkscape: Keine Berechtigung
  1173 ^C
  1174 </pre>
  1175 </td>
  1176 </tr>
  1177 </table>
  1178 <br/>
  1179     </p></li>
  1180     <li><p>
  1181     Команды, выполненные с привилегиями суперпользователя,
  1182     выделяются слева красной чертой.
  1183 <table>
  1184 <tr class='command'>
  1185 <td class='script'>
  1186 <pre class='_root_cline'>
  1187 # id</pre>
  1188 <pre class='_root_output'>
  1189 uid=0(root) gid=0(root) Gruppen=0(root)
  1190 </pre>
  1191 </td>
  1192 </tr>
  1193 </table>
  1194     <br/>
  1195     </p></li>
  1196     <li><p>
  1197     Изменения, внесённые в текстовый файл с помощью редактора, 
  1198     запоминаются и показываются в журнале в формате ed.
  1199     Строки, начинающиеся символом "<", удалены, а строки,
  1200     начинающиеся символом ">" -- добавлены.
  1201 <table>
  1202 <tr class='command'>
  1203 <td class='script'>
  1204 <pre class='cline'>
  1205 \$ vi ~/.bashrc</pre>
  1206 <table><tr><td width='5'/><td class='diff'><pre>2a3,5
  1207 >    if [ -f /usr/local/etc/bash_completion ]; then
  1208 >         . /usr/local/etc/bash_completion
  1209 >        fi
  1210 </pre></td></tr></table></td>
  1211 </tr>
  1212 </table>
  1213     <br/>
  1214     </p></li>
  1215     <li><p>
  1216     Для того чтобы изменить файл в соответствии с показанными в диффшоте
  1217     изменениями, можно воспользоваться командой patch.
  1218     Нужно скопировать изменения, запустить программу patch, указав в
  1219     качестве её аргумента файл, к которому применяются изменения,
  1220     и всавить скопированный текст:
  1221 <table>
  1222 <tr class='command'>
  1223 <td class='script'>
  1224 <pre class='cline'>
  1225 \$ patch ~/.bashrc</pre>
  1226 </td>
  1227 </tr>
  1228 </table>
  1229     В данном случае изменения применяются к файлу ~/.bashrc
  1230     </p></li>
  1231     <li><p>
  1232     Для того чтобы получить краткую справочную информацию о команде, 
  1233     нужно подвести к ней мышь. Во всплывающей подсказке появится краткое
  1234     описание команды.
  1235     </p>
  1236     <p>
  1237     Если справочная информация о команде есть, 
  1238     команда выделяется голубым фоном, например: <span class="with_hint" title="главный текстовый редактор Unix">vi</span>.
  1239     Если справочная информация отсутствует,
  1240     команда выделяется розовым фоном, например: <span class="without_hint">notepad.exe</span>.
  1241     Справочная информация может отсутствовать в том случае, 
  1242     если (1) команда введена неверно; (2) если распознавание команды LiLaLo выполнено неверно;
  1243     (3) если информация о команде неизвестна LiLaLo.
  1244     Последнее возможно для редких команд.
  1245     </p></li>
  1246     <li><p>
  1247     Большие, в особенности многострочные, всплывающие подсказки лучше 
  1248     всего показываются браузерами KDE Konqueror, Apple Safari и Microsoft Internet Explorer.
  1249     В браузерах Mozilla и Firefox они отображаются не полностью, 
  1250     а вместо перевода строки выводится специальный символ.
  1251     </p></li>
  1252     <li><p>
  1253     Время ввода команды, показанное в журнале, соответствует времени 
  1254     <i>начала ввода командной строки</i>, которое равно тому моменту, 
  1255     когда на терминале появилось приглашение интерпретатора
  1256     </p></li>
  1257     <li><p>
  1258     Имя терминала, на котором была введена команда, показано в специальном блоке.
  1259     Этот блок показывается только в том случае, если терминал
  1260     текущей команды отличается от терминала предыдущей.
  1261     </p></li>
  1262     <li><p>
  1263     Вывод не интересующих вас в настоящий момент элементов журнала,
  1264     таких как время, имя терминала и других, можно отключить.
  1265     Для этого нужно воспользоваться <a href='#visibility_form'>формой управления журналом</a>
  1266     вверху страницы.
  1267     </p></li>
  1268     <li><p>
  1269     Небольшие комментарии к командам можно вставлять прямо из командной строки.
  1270     Комментарий вводится прямо в командную строку, после символов #^ или #v.
  1271     Символы ^ и v показывают направление выбора команды, к которой относится комментарий:
  1272     ^ - к предыдущей, v - к следующей.
  1273     Например, если в командной строке было введено:
  1274 <pre class='cline'>
  1275 \$ whoami
  1276 </pre>
  1277 <pre class='output'>
  1278 user
  1279 </pre>
  1280 <pre class='cline'>
  1281 \$ #^ Интересно, кто я?
  1282 </pre>
  1283     в журнале это будет выглядеть так:
  1285 <pre class='cline'>
  1286 \$ whoami
  1287 </pre>
  1288 <pre class='output'>
  1289 user
  1290 </pre>
  1291 <table class='note'><tr><td width='100%' class='note_text'>
  1292 <tr> <td> Интересно, кто я?<br/> </td></tr></table> 
  1293     </p></li>
  1294     <li><p>
  1295     Если комментарий содержит несколько строк,
  1296     его можно вставить в журнал следующим образом:
  1297 <pre class='cline'>
  1298 \$ whoami
  1299 </pre>
  1300 <pre class='output'>
  1301 user
  1302 </pre>
  1303 <pre class='cline'>
  1304 \$ cat > /dev/null #^ Интересно, кто я?
  1305 </pre>
  1306 <pre class='output'>
  1307 Программа whoami выводит имя пользователя, под которым 
  1308 мы зарегистрировались в системе.
  1309 -
  1310 Она не может ответить на вопрос о нашем назначении 
  1311 в этом мире.
  1312 </pre>
  1313     В журнале это будет выглядеть так:
  1314 <table>
  1315 <tr class='command'>
  1316 <td class='script'>
  1317 <pre class='cline'>
  1318 \$ whoami</pre>
  1319 <pre class='output'>user
  1320 </pre>
  1321 <table class='note'><tr><td class='note_title'>Интересно, кто я?</td></tr><tr><td width='100%' class='note_text'>
  1322 Программа whoami выводит имя пользователя, под которым<br/>
  1323 мы зарегистрировались в системе.<br/>
  1324 <br/>
  1325 Она не может ответить на вопрос о нашем назначении<br/>
  1326 в этом мире.<br/>
  1327 </td></tr></table>
  1328 </td>
  1329 </tr>
  1330 </table>
  1331     Для разделения нескольких абзацев между собой
  1332     используйте символ "-", один в строке.
  1333     <br/>
  1334 </p></li>
  1335     <li><p>
  1336     Комментарии, не относящиеся непосредственно ни к какой из команд, 
  1337     добавляются точно таким же способом, только вместо симолов #^ или #v 
  1338     нужно использовать символы #=
  1339     </p></li>
  1340 </ol>
  1341 HELP
  1343 $Html_About = <<ABOUT;
  1344     <p>
  1345     LiLaLo (L3) расшифровывается как Live Lab Log.<br/>
  1346     Программа разработана для повышения эффективности обучения Unix/Linux-системам.<br/>
  1347     (c) Игорь Чубин, 2004-2006<br/>
  1348     </p>
  1349 ABOUT
  1350 $Html_About.='$Id$ </p>';
  1352 $Html_JavaScript = <<JS;
  1353     function getElementsByClassName(Class_Name)
  1354     {
  1355         var Result=new Array();
  1356         var All_Elements=document.all || document.getElementsByTagName('*');
  1357         for (i=0; i<All_Elements.length; i++)
  1358             if (All_Elements[i].className==Class_Name)
  1359         Result.push(All_Elements[i]);
  1360         return Result;
  1361     }
  1362     function ShowHide (name)
  1363     {
  1364         elements=getElementsByClassName(name);
  1365         for(i=0; i<elements.length; i++)
  1366             if (elements[i].style.display == "none")
  1367                 elements[i].style.display = "";
  1368             else
  1369                 elements[i].style.display = "none";
  1370             //if (elements[i].style.visibility == "hidden")
  1371             //  elements[i].style.visibility = "visible";
  1372             //else
  1373             //  elements[i].style.visibility = "hidden";
  1374     }
  1375     function filter_by_output(text)
  1376     {
  1378         var jjj=0;
  1380         elements=getElementsByClassName('command');
  1381         for(i=0; i<elements.length; i++) {
  1382             subelems = elements[i].getElementsByTagName('pre');
  1383             for(j=0; j<subelems.length; j++) {
  1384                 if (subelems[j].className = 'output') {
  1385                     var str = new String(subelems[j].nodeValue);
  1386                     if (jjj != 1) { 
  1387                         alert(str);
  1388                         jjj=1;
  1389                     }
  1390                     if (str.indexOf(text) >0) 
  1391                         subelems[j].style.display = "none";
  1392                     else
  1393                         subelems[j].style.display = "";
  1395                 }
  1397             }
  1398         }       
  1400     }
  1401 JS
  1403 %Search_Machines = (
  1404         "google" =>     {   "query" =>  "http://www.google.com/search?q=" ,
  1405                     "icon"  =>  "$Config{frontend_google_ico}" },
  1406         "freebsd" =>    {   "query" =>  "http://www.freebsd.org/cgi/man.cgi?query=",
  1407                     "icon"  =>  "$Config{frontend_freebsd_ico}" },
  1408         "linux"  =>     {   "query" =>  "http://man.he.net/?topic=",
  1409                     "icon"  =>  "$Config{frontend_linux_ico}"},
  1410         "opennet"  =>   {   "query" =>  "http://www.opennet.ru/search.shtml?words=",
  1411                     "icon"  =>  "$Config{frontend_opennet_ico}"},
  1412         "local" =>  {   "query" =>  "http://www.freebsd.org/cgi/man.cgi?query=",
  1413                     "icon"  =>  "$Config{frontend_local_ico}" },
  1415     );
  1417 %Elements_Visibility = (
  1418         "0 new_commands_table"      =>  "новые команды",
  1419         "1 diff"      =>  "редактор",
  1420         "2 time"      =>  "время",
  1421         "3 ttychange"     =>  "терминал",
  1422         "4 wrong_output wrong_cline wrong_root_output wrong_root_cline" 
  1423                 =>  "команды с ненулевым кодом завершения",
  1424         "5 mistyped_output mistyped_cline mistyped_root_output mistyped_root_cline" 
  1425                 =>  "неверно набранные команды",
  1426         "6 interrupted_output interrupted_cline interrupted_root_output interrupted_root_cline" 
  1427                 =>  "прерванные команды",
  1428         "7 tab_completion_output tab_completion_cline"    
  1429                 =>  "продолжение с помощью tab"
  1430 );
  1432 @Day_Name      = qw/ Воскресенье Понедельник Вторник Среда Четверг Пятница Суббота /;
  1433 @Month_Name    = qw/ Январь Февраль Март Апрель Май Июнь Июль Август Сентябрь Октябрь Ноябрь Декабрь /;
  1434 @Of_Month_Name = qw/ Января Февраля Марта Апреля Мая Июня Июля Августа Сентября Октября Ноября Декабря /;
  1435 }
  1440 # Временно удалённый код
  1441 # Возможно, он не понадобится уже никогда
  1444 sub search_by
  1445 {
  1446     my $sm = shift;
  1447     my $topic = shift;
  1448     $topic =~ s/ /+/;
  1450     return "<a href='". $Search_Machines{$sm}->{"query"}."$topic'><img width='16' height='16' src='".
  1451                 $Search_Machines{$sm}->{"icon"}."' border='0'/></a>";
  1452 }
