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