lilalo
view l3-frontend @ 101:c41cc9a4b5ea
* Пофиксил ошибку с неправильной кодировкой mywi-хинтов.
* Подготовил к переходу в иерархию /l3/
** Исправил пути для стилей,
** Забацал красивый l3-cgi-lite
l3-cgi-lite пока что не доделан до нужного уровня,
но я его скоро дорисую.
Уже сейчас это намного более качественный скрипт
через уродский l3-cgi
Он, конечно, поработал в свое время,
но лучше его заменить l3-cgi-lite
Из функционала добавилось:
* Кэширование страниц в html
* Навигация по каталогам
* Навигационная строка в журнале сверху
* Подготовил к переходу в иерархию /l3/
** Исправил пути для стилей,
** Забацал красивый l3-cgi-lite
l3-cgi-lite пока что не доделан до нужного уровня,
но я его скоро дорисую.
Уже сейчас это намного более качественный скрипт
через уродский l3-cgi
Он, конечно, поработал в свое время,
но лучше его заменить l3-cgi-lite
Из функционала добавилось:
* Кэширование страниц в html
* Навигация по каталогам
* Навигационная строка в журнале сверху
| author | devi | 
|---|---|
| date | Sat Jun 24 22:53:37 2006 +0300 (2006-06-24) | 
| parents | 05e99d32f1f5 | 
| children | 6fce4641575b | 
 line source
     1 #!/usr/bin/perl -w
     3 use IO::Socket;
     4 use lib '.';
     5 use l3config;
     6 use utf8;
     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 %filter;
    16 our $filter_url;
    17 sub init_filter;
    19 our %Files;
    21 # vvv Инициализация переменных выполняется процедурой init_variables
    22 our @Day_Name;
    23 our @Month_Name;
    24 our @Of_Month_Name;
    25 our %Search_Machines;
    26 our %Elements_Visibility;
    27 # ^^^
    29 our %Stat;
    30 our %frequency_of_command; # Сколько раз в журнале встречается какая команда
    31 our $table_number=1;
    33 my %mywi_cache_for;         # Кэш для экономии обращений к mywi
    35 sub make_comment;
    36 sub make_new_entries_table;
    37 sub load_command_lines_from_xml;
    38 sub load_sessions_from_xml;
    39 sub sort_command_lines;
    40 sub process_command_lines;
    41 sub init_variables;
    42 sub main;
    43 sub collapse_list($);
    45 sub minutes_passed;
    47 sub print_all_txt;
    48 sub print_all_html;
    49 sub print_edit_all_html;
    50 sub print_command_lines_html;
    51 sub print_command_lines_txt;
    52 sub print_files_html;
    53 sub print_stat_html;
    54 sub print_header_html;
    55 sub print_footer_html;
    57 main();
    59 sub main
    60 {
    61     $| = 1;
    63     init_variables();
    64     init_config();
    65     $Config{frontend_ico_path}=$Config{frontend_css};
    66     $Config{frontend_ico_path}=~s@/[^/]*$@@;
    67     init_filter();
    69     open_mywi_socket();
    70     load_command_lines_from_xml($Config{"backend_datafile"});
    71     load_sessions_from_xml($Config{"backend_datafile"});
    72     sort_command_lines;
    73     process_command_lines;
    74     if (defined($filter{action}) && $filter{action} eq "edit") {
    75         print_edit_all_html($Config{"output"});
    76     }
    77     else {
    78         print_all_html($Config{"output"});
    79     }
    80     close_mywi_socket;
    81 }
    83 sub init_filter
    84 {
    85     if ($Config{filter}) {
    86         # Инициализация фильтра
    87         for (split /&/,$Config{filter}) {
    88             my ($var, $val) = split /=/;
    89             $filter{$var} = $val || "";
    90         }
    91     }
    92     $filter_url = join ("&", map("$_=$filter{$_}", keys %filter));
    93 }
    95 # extract_from_cline
    97 # In:   $what       = commands | args
    98 # Out:  return      ссылка на хэш, содержащий результаты разбора
    99 #                   команда => позиция
   101 # Разобрать командную строку $_[1] и возвратить хэш, содержащий 
   102 # номер первого появление команды в строке:
   103 #   команда => первая позиция
   104 sub extract_from_cline
   105 {
   106     my $what = $_[0];
   107     my $cline = $_[1];
   108     my @lists = split /\;/, $cline;
   111     my @command_lines = ();
   112     for my $command_list (@lists) {
   113         push(@command_lines, split(/\|/, $command_list));
   114     }
   116     my %position_of_command;
   117     my %position_of_arg;
   118     my $i=0;
   119     for my $command_line (@command_lines) {
   120         $command_line =~ s@^\s*@@;
   121         $command_line =~ /\s*(\S+)\s*(.*)/;
   122         if ($1 && $1 eq "sudo" ) {
   123             $position_of_command{"$1"}=$i++;
   124             $command_line =~ s/\s*sudo\s+//;
   125         }
   126         if ($command_line !~ m@^\s*\S*/etc/@) {
   127             $command_line =~ s@^\s*\S+/@@;
   128         }
   130         $command_line =~ /\s*(\S+)\s*(.*)/;
   131         my $command = $1;
   132         my $args = $2;
   133         if ($command && !defined $position_of_command{"$command"}) {
   134                 $position_of_command{"$command"}=$i++;
   135         };  
   136         if ($args) {
   137             my @args = split (/\s+/, $args);
   138             for my $a (@args) {
   139                 $position_of_arg{"$a"}=$i++
   140                     if !defined $position_of_arg{"$a"};
   141             };  
   142         }
   143     }
   145     if ($what eq "commands") {
   146         return \%position_of_command;
   147     } else {
   148         return \%position_of_arg;
   149     }
   151 }
   156 #
   157 # Подпрограммы для работы с mywi
   158 #
   160 sub open_mywi_socket
   161 {
   162     $Mywi_Socket = IO::Socket::INET->new(
   163                 PeerAddr => $Config{mywi_server},
   164                 PeerPort => $Config{mywi_port},
   165                 Proto    => "tcp",
   166                 Type     => SOCK_STREAM);
   167 }
   169 sub close_mywi_socket
   170 {
   171     close ($Mywi_Socket) if $Mywi_Socket ;
   172 }
   175 sub mywi_client
   176 {
   177     #return "";
   178     my $query = $_[0];
   179     my $mywi;
   181     open_mywi_socket;
   182     if ($Mywi_Socket) {
   183         binmode ":utf8", $Mywi_Socket;
   184         local $| = 1;
   185         local $/ = "";
   186         print $Mywi_Socket $query."\n";
   187         $mywi = <$Mywi_Socket>;
   188         utf8::decode($mywi);
   189         $mywi = "" if $mywi =~ /nothing app/;
   190     }
   191     close_mywi_socket;
   192     return $mywi;
   193 }
   195 sub make_comment
   196 {
   197     my $cline = $_[0];
   198     #my $files = $_[1];
   200     my @comments;
   201     my @commands = keys %{extract_from_cline("commands", $cline)};
   202     my @args = keys %{extract_from_cline("args", $cline)};
   203     return if (!@commands && !@args);
   204     #return "commands=".join(" ",@commands)."; files=".join(" ",@files);
   206     # Commands
   207     for my $command (@commands) {
   208         $command =~ s/'//g;
   209         $frequency_of_command{$command}++;
   210         if (!$Commands_Description{$command}) {
   211             $mywi_cache_for{$command} ||= mywi_client ($command) || "";
   212             my $mywi = join ("\n", grep(/\([18]|sh|script\)/, split(/\n/, $mywi_cache_for{$command})));
   213             $mywi =~ s/\s+/ /;
   214             if ($mywi !~ /^\s*$/) {
   215                 $Commands_Description{$command} = $mywi;
   216             }
   217             else {
   218                 next;
   219             }
   220         }
   222         push @comments, $Commands_Description{$command};
   223     }
   224     return join("
\n", @comments);
   226     # Files
   227     for my $arg (@args) {
   228         $arg =~ s/'//g;
   229         if (!$Args_Description{$arg}) {
   230             my $mywi;
   231             $mywi = mywi_client ($arg);
   232             $mywi = join ("\n", grep(/\([5]\)/, split(/\n/, $mywi)));
   233             $mywi =~ s/\s+/ /;
   234             if ($mywi !~ /^\s*$/) {
   235                 $Args_Description{$arg} = $mywi;
   236             }
   237             else {
   238                 next;
   239             }
   240         }
   242         push @comments, $Args_Description{$arg};
   243     }
   245 }
   247 =cut
   248 Процедура load_command_lines_from_xml выполняет загрузку разобранного lab-скрипта
   249 из XML-документа в переменную @Command_Lines
   251 # In:       $datafile           имя файла
   252 # Out:      @CommandLines       загруженные командные строки
   254 Предупреждение!
   255 Процедура не в состоянии обрабатывать XML-документ любой структуры.
   256 В действительности файл cache из которого загружаются данные 
   257 просто напоминает XML с виду.
   258 =cut
   259 sub load_command_lines_from_xml
   260 {
   261     my $datafile = $_[0];
   263     open (CLASS, $datafile)
   264         or die "Can't open file with xml lablog ",$datafile,"\n";
   265     local $/;
   266     binmode CLASS, ":utf8";
   267     $data = <CLASS>;
   268     close(CLASS);
   270     for $command ($data =~ m@<command>(.*?)</command>@sg) {
   271         my %cl;
   272         while ($command =~ m@<([^>]*?)>(.*?)</\1>@sg) {
   273             $cl{$1} = $2;
   274         }
   275         push @Command_Lines, \%cl;
   276     }
   277 }
   279 sub load_sessions_from_xml
   280 {
   281     my $datafile = $_[0];
   283     open (CLASS,  $datafile)
   284         or die "Can't open file with xml lablog ",$datafile,"\n";
   285     local $/;
   286     binmode CLASS, ":utf8";
   287     my $data = <CLASS>;
   288     close(CLASS);
   290     my $i=0;
   291     for my $session ($data =~ m@<session>(.*?)</session>@msg) {
   292         my %session_hash;
   293         while ($session =~ m@<([^>]*?)>(.*?)</\1>@sg) {
   294             $session_hash{$1} = $2;
   295         }
   296         $Sessions{$session_hash{local_session_id}} = \%session_hash;
   297     }
   298 }
   301 # sort_command_lines
   302 # In:   @Command_Lines
   303 # Out:  @Command_Lies_Index
   305 sub sort_command_lines
   306 {
   308     my @index;
   309     for (my $i=0;$i<=$#Command_Lines;$i++) {
   310         $index[$i]=$i;
   311     }
   313     @Command_Lines_Index = sort {
   314         $Command_Lines[$index[$a]]->{"time"} <=> $Command_Lines[$index[$b]]->{"time"}
   315     } @index;
   317 }
   319 ##################
   320 # process_command_lines
   321 #
   322 # Обрабатываются командные строки @Command_Lines
   323 # Для каждой строки определяется:
   324 #   class   класс    
   325 #   note    комментарий 
   326 #
   327 # In:        @Command_Lines_Index
   328 # In-Out:    @Command_Lines
   330 sub process_command_lines
   331 {
   333 COMMAND_LINE_PROCESSING:
   334     for my $i (@Command_Lines_Index) {
   335         my $cl = \$Command_Lines[$i];
   337         next if !$cl;
   339         for my $filter_key (keys %filter) {
   340             next COMMAND_LINE_PROCESSING
   341                 if defined($$cl->{local_session_id})
   342                 && defined($Sessions{$$cl->{local_session_id}}->{$filter_key})
   343                 && $Sessions{$$cl->{local_session_id}}->{$filter_key} ne $filter{$filter_key};
   344         }
   346         $$cl->{id} = $$cl->{"time"};
   348         $$cl->{err} ||=0;
   350         # Класс команды
   352         $$cl->{"class"} =   $$cl->{"err"} eq 130 ?  "interrupted"
   353                         :   $$cl->{"err"} eq 127 ?  "mistyped"
   354                         :   $$cl->{"err"}        ?  "wrong"
   355                         :                           "normal";
   357         if ($$cl->{"cline"} && 
   358             $$cl->{"cline"} =~ /[^|`]\s*sudo/
   359             || $$cl->{"uid"} eq 0) {
   360             $$cl->{"class"}.="_root";
   361         }
   363         my $hint;
   364         $hint = make_comment($$cl->{"cline"});
   365         if ($hint) {
   366             $$cl->{hint} = $hint;
   367         }
   368 #        $$cl->{hint}="";
   370 # Выводим <head_lines> верхних строк
   371 # и <tail_lines> нижних строк,
   372 # если эти параметры существуют
   373         my $output="";
   375         if ($$cl->{"last_command"} eq "cat" && !$$cl->{"err"} && !($$cl->{"cline"} =~ /</)) {
   376             my $filename = $$cl->{"cline"};
   377             $filename =~ s/.*\s+(\S+)\s*$/$1/;
   378             $Files{$filename}->{"content"} = $$cl->{"output"};
   379            $Files{$filename}->{"source_command_id"} = $$cl->{"id"}
   380         }
   381         my @lines = split '\n', $$cl->{"output"};
   382         if ((
   383              $Config{"head_lines"} 
   384              || $Config{"tail_lines"}
   385              )
   386              && $#lines >  $Config{"head_lines"} + $Config{"tail_lines"} ) {
   387 #
   388             for (my $i=0; $i<= $#lines && $i < $Config{"head_lines"}; $i++) {
   389                 $output .= $lines[$i]."\n";
   390             }
   391             $output .= $Config{"skip_text"}."\n";
   393             my $start_line=$#lines-$Config{"tail_lines"}+1;
   394             for (my $i=$start_line; $i<= $#lines; $i++) {
   395                 $output .= $lines[$i]."\n";
   396             }
   397         } 
   398         else {
   399            $output = $$cl->{"output"};
   400         }
   401         $$cl->{short_output} = $output;
   403 #Обработка пометок
   404 #  Если несколько пометок (notes) идут подряд, 
   405 #  они все объединяются
   407         if ($$cl->{cline} =~ /l3shot/) {
   408                 if ($$cl->{output} =~ m@Screenshot is written to.*/(.*)\.xwd@) {
   409                     $$cl->{screenshot}="$1";
   410                 }
   411         }
   413         if ($$cl->{cline}=~ m@cat[^#]*#([\^=v])\s*(.*)@) {
   415             my $note_operator = $1;
   416             my $note_title = $2;
   418             if ($note_operator eq "=") {
   419                 $$cl->{"class"} = "note";
   420                 $$cl->{"note"} = $$cl->{"output"};
   421                 $$cl->{"note_title"} = $2;
   422             }
   423             else {
   424                 my $j = $i;
   425                 if ($note_operator eq "^") {
   426                     $j--;
   427                     $j-- while ($j >=0  && (!$Command_Lines[$j] || $Command_Lines[$j]->{tty} ne $$cl->{tty}));
   428                 }
   429                 elsif ($note_operator eq "v") {
   430                     $j++;
   431                     $j++ while ($j <= @Command_Lines  && (!$Command_Lines[$j] || $Command_Lines[$j]->{tty} ne $$cl->{tty}));
   432                 }
   433                 $Command_Lines[$j]->{note_title}=$note_title;
   434                 $Command_Lines[$j]->{note}.=$$cl->{output};
   435                 $$cl=0;
   436             }
   437         }
   438         elsif ($$cl->{cline}=~ /#([\^=v])(.*)/) {
   440             my $note_operator = $1;
   441             my $note_text = $2;
   443             if ($note_operator eq "=") {
   444                 $$cl->{"class"} = "note";
   445                 $$cl->{"note"} = $note_text;
   446             }
   447             else {
   448                 my $j=$i;
   449                 if ($note_operator eq "^") {
   450                     $j--;
   451                     $j-- while ($j >=0  && (!$Command_Lines[$j] || $Command_Lines[$j]->{tty} ne $$cl->{tty}));
   452                 }
   453                 elsif ($note_operator eq "v") {
   454                     $j++;
   455                     $j++ while ($j <= @Command_Lines  && $Command_Lines[$j]->{tty} ne $$cl->{tty} || !$Command_Lines[$j]);
   456                 }
   457                 $Command_Lines[$j]->{note}.="$note_text\n";
   458                 $$cl=0;
   459             }
   460         }
   461         if ($$cl->{"class"} eq "note") {
   462                 my $note_html = $$cl->{note};
   463                 $note_html = join ("\n", map ("<p>$_</p>", split (/-\n/, $note_html)));
   464                 $note_html =~ s@(http:[a-zA-Z.0-9/?\_%-]*)@<a href='$1'>$1</a>@g;
   465                 $note_html =~ s@(www\.[a-zA-Z.0-9/?\_%-]*)@<a href='$1'>$1</a>@g;
   466                 $$cl->{"note_html"} = $note_html;
   467         }
   468     }   
   470 }
   473 =cut
   474 Процедура print_command_lines выводит HTML-представление
   475 разобранного lab-скрипта. 
   477 Разобранный lab-скрипт должен находиться в массиве @Command_Lines
   478 =cut
   480 sub print_command_lines_html
   481 {
   483     my @toc;                # Оглавление
   484     my $note_number=0;
   486     my $result = q();
   487     my $this_day_resut = q();
   489     my $cl;
   490     my $last_tty="";
   491     my $last_session="";
   492     my $last_day=q();
   493     my $last_wday=q();
   494     my $in_range=0;
   496     my $current_command=0;
   498     my @known_commands;
   502     $Stat{LastCommand}   ||= 0;
   503     $Stat{TotalCommands} ||= 0;
   504     $Stat{ErrorCommands} ||= 0;
   505     $Stat{MistypedCommands} ||= 0;
   507     my %new_entries_of = (
   508         "1 1"     =>   "программы пользователя",
   509         "2 8"     =>   "программы администратора",
   510         "3 sh"    =>   "команды интерпретатора",
   511         "4 script"=>   "скрипты",
   512     );
   514 COMMAND_LINE:
   515     for my $k (@Command_Lines_Index) {
   517         my $cl=$Command_Lines[$Command_Lines_Index[$current_command++]];
   518         next unless $cl;
   520 # Пропускаем команды, с одинаковым временем
   521 # Это не совсем правильно.
   522 # Возможно, что это команды, набираемые с помощью <completion>
   523 # или запомненные с помощью <ctrl-c>
   525         next if $Stat{LastCommand} == $cl->{time};
   527 # Пропускаем строки, которые противоречат фильтру
   528 # Если у нас недостаточно информации о том, подходит строка под  фильтр или нет, 
   529 # мы её выводим
   531         for my $filter_key (keys %filter) {
   532             next COMMAND_LINE 
   533                 if defined($cl->{local_session_id})
   534                 && defined($Sessions{$cl->{local_session_id}}->{$filter_key})
   535                 && $Sessions{$cl->{local_session_id}}->{$filter_key} ne $filter{$filter_key};
   536         }
   538 # Набираем статистику
   539 # Хэш %Stat
   541         $Stat{FirstCommand} = $cl->{time} unless $Stat{FirstCommand};
   542         if ($cl->{time} - $Stat{LastCommand} < $Config{stat_inactivity_interval}) {
   543             $Stat{TotalTime} += $cl->{time} - $Stat{LastCommand}
   544         }
   545         my $seconds_since_last_command = $cl->{time} - $Stat{LastCommand};
   547         if ($Stat{LastCommand} > $cl->{time}) {
   548                $result .= "Время идёт вспять<br/>";
   549         };
   550         $Stat{LastCommand} = $cl->{time};
   551         $Stat{TotalCommands}++;
   553 # Пропускаем строки, выходящие за границу "signature",
   554 # при условии, что границы указаны
   555 # Пропускаем неправильные/прерванные/другие команды
   556         if ($Config{"from"} && $cl->{"cline"} =~ /$Config{"signature"}\s*$Config{"from"}/) {
   557             $in_range=1;
   558             next;
   559         }
   560         if ($Config{"to"} && $cl->{"cline"} =~ /$Config{"signature"}\s*$Config{"to"}/) {
   561             $in_range=0;
   562             next;
   563         }
   564         next    if ($Config{"from"} && $Config{"to"}   && !$in_range) 
   565                 || ($Config{"skip_empty"} =~ /^y/i     && $cl->{"cline"} =~ /^\s*$/ )
   566                 || ($Config{"skip_wrong"} =~ /^y/i     && $cl->{"err"} != 0)
   567                 || ($Config{"skip_interrupted"} =~ /^y/i && $cl->{"err"} == 130);
   572 #
   573 ##
   574 ## Начинается собственно вывод
   575 ##
   576 #
   578 ### Сначала обрабатываем границы разделов
   579 ### Если тип команды "note", это граница
   581         if ($cl->{class} eq "note") {
   582             $this_day_result .= "<tr><td colspan='6'>"
   583                              .  "<h4 id='note$note_number'>".$cl->{note_title}."</h4>" if $cl->{note_title}
   584                              .  "".$cl->{note_html}."<p/><p/></td></tr>";
   586             if ($cl->{note_title}) {
   587                 push @{$toc[@toc]},"<a href='#note$note_number'>".$cl->{note_title}."</a>";
   588                 $note_number++;
   589             }
   590             next;
   591         }
   593         my ($sec,$min,$hour,$day,$mon,$year,$wday,$yday,$isdst) = localtime($cl->{time});
   595         # Добавляем спереди 0 для удобочитаемости
   596         $min  = "0".$min  if $min  =~ /^.$/;
   597         $hour = "0".$hour if $hour =~ /^.$/;
   598         $sec  = "0".$sec  if $sec  =~ /^.$/;
   600         $class=$cl->{"class"};
   601         $Stat{ErrorCommands}++          if $class =~ /wrong/;
   602         $Stat{MistypedCommands}++       if $class =~ /mistype/;
   604 # DAY CHANGE
   605         if ( $last_day ne $day) {
   606             if ($last_day) {
   608 # Вычисляем разность множеств.
   609 # Что-то вроде этого, если бы так можно было писать:
   610 #   @new_commands = keys %frequency_of_command - @known_commands;
   613                 $result .= "<h3 id='day$last_day'>".$Day_Name[$last_wday]."</h3>";
   614                 for my $entry_class (sort keys %new_entries_of) {
   615                     my $table_caption = "Таблица ".$table_number++.".".$Day_Name[$last_wday]
   616                                         .". Новые ".$new_entries_of{$entry_class};
   617                     my $new_commands_section = make_new_entries_table(
   618                                                 $table_caption, 
   619                                                 $entry_class=~/[0-9]+\s+(.*)/, 
   620                                                 \@known_commands);
   621                 }
   622                 @known_commands = keys %frequency_of_command;
   623                 $result .= $this_day_result;
   624             }
   626             push @toc, "<a href='#day$day'>".$Day_Name[$wday]."</a>\n";
   627             $last_day=$day;
   628             $last_wday=$wday;
   629             $this_day_result = q();
   630         }
   631         else {
   632             $this_day_result .= minutes_passed($seconds_since_last_command);
   633         }
   635         $this_day_result .= "<div class='command' id='command:".$cl->{"id"}."' >\n";
   637 # CONSOLE CHANGE
   638         if ($cl->{"tty"} && $last_tty ne $cl->{"tty"} && 0) {
   639             my $tty = $cl->{"tty"};
   640             $this_day_result .= "<div class='ttychange'>"
   641                                 . $tty
   642                                 ."</div>";
   643             $last_tty=$cl->{"tty"};
   644         }
   646 # Session change
   647         if ( $last_session ne $cl->{"local_session_id"}) {
   648             my $tty;
   649             if (defined $Sessions{$cl->{"local_session_id"}}->{"tty"}) {
   650                 $this_day_result .= "<div class='ttychange'><a href='?local_session_id=".$cl->{"local_session_id"}."'>"
   651                                 . $Sessions{$cl->{"local_session_id"}}->{"tty"}
   652                                 ."</a></div>";
   653             }
   654             $last_session=$cl->{"local_session_id"};
   655         }
   657 # TIME
   658         if ($Config{"show_time"} =~ /^y/i) {
   659             $this_day_result .= "<div class='time'>$hour:$min:$sec</div>" 
   660         }
   662 # COMMAND
   663         my $cline;
   664         $prompt_hint = join ("
", map("$_=$cl->{$_}", grep (!/^(output|diff)$/, sort(keys(%{$cl})))));
   665         $cline = "<span title='$prompt_hint'>".$cl->{"prompt"}."</span>".$cl->{"cline"};
   666         $cline =~ s/\n//;
   668         if ($cl->{"hint"}) {
   669             $cline = "<span title='$cl->{hint}' class='with_hint'>$cline</span>" ;
   670         } 
   671         else {
   672             $cline = "<span class='without_hint'>$cline</span>";
   673         }
   675         $this_day_result .= "<table cellpadding='0' cellspacing='0'><tr><td>\n<div class='cblock_$cl->{class}'>\n";
   676         $this_day_result .= "<div class='cline'>\n" . $cline ;      #cline
   677         $this_day_result .= "<span title='Код завершения ".$cl->{"err"}."'>\n"
   678                          .  "<img src='".$Config{frontend_ico_path}."/error.png'/>\n"
   679                          .  "</span>\n" if $cl->{"err"};
   680         $this_day_result .= "</div>\n";                             #cline
   682 # OUTPUT
   683         my $last_command = $cl->{"last_command"};
   684         if (!( 
   685         $Config{"suppress_editors"} =~ /^y/i && grep ($_ eq $last_command, @{$Config{"editors"}}) ||
   686         $Config{"suppress_pagers"}  =~ /^y/i && grep ($_ eq $last_command, @{$Config{"pagers"}}) ||
   687         $Config{"suppress_terminal"}=~ /^y/i && grep ($_ eq $last_command, @{$Config{"terminal"}})
   688             )) {
   689             $this_day_result .= "<pre class='output'>\n" . $cl->{short_output} . "</pre>\n";
   690         }
   692 # DIFF
   693         $this_day_result .= "<pre class='diff'>".$cl->{"diff"}."</pre>"
   694             if ( $Config{"show_diffs"} =~ /^y/i && $cl->{"diff"});
   695 # SHOT
   696         $this_day_result .= "<img src='"
   697                 .$Config{l3shot_path}
   698                 .$cl->{"screenshot"}
   699                 .$Config{l3shot_suffix}
   700                 ."' alt ='screenshot id ".$cl->{"screenshot"}
   701                 ."'/>"
   702             if ( $Config{"show_screenshots"} =~ /^y/i && $cl->{"screenshot"});
   704 #NOTES
   705         if ( $Config{"show_notes"} =~ /^y/i && $cl->{"note"}) {
   706             my $note=$cl->{"note"};
   707             $note =~ s/\n/<br\/>\n/msg;
   708             if (not $note =~ s@(http:[a-zA-Z.0-9/_?%-]*)@<a href='$1'>$1</a>@g) {
   709               $note =~ s@(www\.[a-zA-Z.0-9/_?%-]*)@<a href='$1'>$1</a>@g;
   710             };
   711             $this_day_result .= "<div class='note'>";
   712             $this_day_result .= "<div class='note_title'>".$cl->{note_title}."</div>" if $cl->{note_title};
   713             $this_day_result .= "<div class='note_text'>".$note."</div>";
   714             $this_day_result .= "</div>\n";
   715         }
   717         # Вывод очередной команды окончен
   718         $this_day_result .= "</div>\n";                     # cblock
   719         $this_day_result .= "</td></tr></table>\n"
   720                          .  "</div>\n";                     # command
   721     }
   722     last: {
   723         $result .= "<h3 id='day$last_day'>".$Day_Name[$last_wday]."</h3>";
   725         for my $entry_class (keys %new_entries_of) {
   726             my $table_caption = "Таблица ".$table_number++.".".$Day_Name[$last_wday]
   727                               . ". Новые ".$new_entries_of{$entry_class};
   728             my $new_commands_section = make_new_entries_table(
   729                                         $table_caption, 
   730                                         $entry_class=~/[0-9]+\s+(.*)/, 
   731                                         \@known_commands);
   732         }
   733         @known_commands = keys %frequency_of_command;
   734         $result .= $this_day_result;
   735    }
   737     return ($result, collapse_list (\@toc));
   739 }
   741 #############
   742 # make_new_entries_table
   743 #
   744 # Напечатать таблицу неизвестных команд
   745 #
   746 # In:       $_[0]       table_caption
   747 #           $_[1]       entries_class
   748 #           @_[2..]     known_commands
   749 # Out:
   751 sub make_new_entries_table
   752 {
   753     my $table_caption;
   754     my $entries_class = shift;
   755     my @known_commands = @{$_[0]};
   756     my $result = "";
   758     my %count;
   759     my @new_commands = ();
   760     for my $c (keys %frequency_of_command, @known_commands) {
   761         $count{$c}++
   762     }
   763     for my $c (keys %frequency_of_command) {
   764         push @new_commands, $c if $count{$c} != 2;
   765     }
   767     my $new_commands_section;
   768     if (@new_commands){
   769         my $hint;
   770         for my $c (reverse sort { $frequency_of_command{$a} <=> $frequency_of_command{$b} } @new_commands) {
   771                 $hint = make_comment($c);
   772                 next unless $hint;
   773                 my ($command, $hint) = $hint =~ m/(.*?) \s*- \s*(.*)/;
   774                 next unless $command =~ s/\($entries_class\)//i;
   775                 $new_commands_section .= "<tr><td valign='top'>$command</td><td>$hint</td></tr>";
   776         }
   777     }
   778     if ($new_commands_section) {
   779         $result .= "<table class='new_commands_table' width='700' cellspacing='0' cellpadding='0'>"
   780                 .  "<tr class='new_commands_caption'>"
   781                 .  "<td colspan='2' align='right'>$table_caption</td>"
   782                 .  "</tr>"
   783                 .  "<tr class='new_commands_header'>"
   784                 .  "<td width=100>Команда</td><td width=600>Описание</td>"
   785                 .  "</tr>"
   786                 .  $new_commands_section 
   787                 .  "</table>"
   788     }
   789     return $result;
   790 }
   792 #############
   793 # minutes_passed
   794 #
   795 #
   796 #
   797 # In:       $_[0]       seconds_since_last_command
   798 # Out:                  "minutes passed" text
   800 sub minutes_passed
   801 {
   802         my $seconds_since_last_command = shift;
   803         my $result = "";
   804         if ($seconds_since_last_command > 7200) {
   805             my $hours_passed =  int($seconds_since_last_command/3600);
   806             my $passed_word  = $hours_passed % 10 == 1 ? "прошла"
   807                                                          : "прошло";
   808             my $hours_word   = $hours_passed % 10 == 1 ?   "часа":
   809                                                            "часов";
   810             $result .= "<div class='much_time_passed'>"
   811                     .  $passed_word." >".$hours_passed." ".$hours_word
   812                     .  "</div>\n";
   813         }
   814         elsif ($seconds_since_last_command > 600) {
   815             my $minutes_passed =  int($seconds_since_last_command/60);
   818             my $passed_word  = $minutes_passed % 100 > 10 
   819                             && $minutes_passed % 100 < 20 ? "прошло"
   820                              : $minutes_passed % 10 == 1  ? "прошла"
   821                                                           : "прошло";
   823             my $minutes_word = $minutes_passed % 100 > 10 
   824                             && $minutes_passed % 100 < 20 ? "минут" :
   825                                $minutes_passed % 10 == 1 ? "минута":
   826                                $minutes_passed % 10 == 0 ? "минут" :
   827                                $minutes_passed % 10  > 4 ? "минут" :
   828                                                            "минуты";
   830             if ($seconds_since_last_command < 1800) {
   831                 $result .= "<div class='time_passed'>"
   832                         .  $passed_word." ".$minutes_passed." ".$minutes_word
   833                         .  "</div>\n";
   834             }
   835             else {
   836                 $result .= "<div class='much_time_passed'>"
   837                         .  $passed_word." ".$minutes_passed." ".$minutes_word
   838                         .  "</div>\n";
   839             }
   840         }
   841         return $result;
   842 }
   844 #############
   845 # print_all_txt
   846 #
   847 # Вывести журнал в текстовом формате
   848 #
   849 # In:       $_[0]       output_filename
   850 # Out:
   852 sub print_command_lines_txt
   853 {
   855     my $output_filename=$_[0];
   856     my $note_number=0;
   858     my $result = q();
   859     my $this_day_resut = q();
   861     my $cl;
   862     my $last_tty="";
   863     my $last_session="";
   864     my $last_day=q();
   865     my $last_wday=q();
   866     my $in_range=0;
   868     my $current_command=0;
   870     my $cursor_position = 0;
   873     if ($Config{filter}) {
   874         # Инициализация фильтра
   875         for (split /&/,$Config{filter}) {
   876             my ($var, $val) = split /=/;
   877             $filter{$var} = $val || "";
   878         }
   879     }
   882 COMMAND_LINE:
   883     for my $k (@Command_Lines_Index) {
   885         my $cl=$Command_Lines[$Command_Lines_Index[$current_command++]];
   886         next unless $cl;
   889 # Пропускаем строки, которые противоречат фильтру
   890 # Если у нас недостаточно информации о том, подходит строка под  фильтр или нет, 
   891 # мы её выводим
   893         for my $filter_key (keys %filter) {
   894             next COMMAND_LINE 
   895                 if defined($cl->{local_session_id})
   896                 && defined($Sessions{$cl->{local_session_id}}->{$filter_key})
   897                 && $Sessions{$cl->{local_session_id}}->{$filter_key} ne $filter{$filter_key};
   898         }
   900 # Пропускаем строки, выходящие за границу "signature",
   901 # при условии, что границы указаны
   902 # Пропускаем неправильные/прерванные/другие команды
   903         if ($Config{"from"} && $cl->{"cline"} =~ /$Config{"signature"}\s*$Config{"from"}/) {
   904             $in_range=1;
   905             next;
   906         }
   907         if ($Config{"to"} && $cl->{"cline"} =~ /$Config{"signature"}\s*$Config{"to"}/) {
   908             $in_range=0;
   909             next;
   910         }
   911         next    if ($Config{"from"} && $Config{"to"}   && !$in_range) 
   912                 || ($Config{"skip_empty"} =~ /^y/i     && $cl->{"cline"} =~ /^\s*$/ )
   913                 || ($Config{"skip_wrong"} =~ /^y/i     && $cl->{"err"} != 0)
   914                 || ($Config{"skip_interrupted"} =~ /^y/i && $cl->{"err"} == 130);
   917 #
   918 ##
   919 ## Начинается собственно вывод
   920 ##
   921 #
   923 ### Сначала обрабатываем границы разделов
   924 ### Если тип команды "note", это граница
   926         if ($cl->{class} eq "note") {
   927             $this_day_result .= " === ".$cl->{note_title}." === \n" if $cl->{note_title};
   928             $this_day_result .= $cl->{note}."\n";
   929             next;
   930         }
   932         my ($sec,$min,$hour,$day,$mon,$year,$wday,$yday,$isdst) = localtime($cl->{time});
   934         # Добавляем спереди 0 для удобочитаемости
   935         $min  = "0".$min  if $min  =~ /^.$/;
   936         $hour = "0".$hour if $hour =~ /^.$/;
   937         $sec  = "0".$sec  if $sec  =~ /^.$/;
   939         $class=$cl->{"class"};
   941 # DAY CHANGE
   942         if ( $last_day ne $day) {
   943             if ($last_day) {
   944                 $result .= "== ".$Day_Name[$last_wday]." == \n";
   945                 $result .= $this_day_result;
   946             }
   947             $last_day   = $day;
   948             $last_wday  = $wday;
   949             $this_day_result = q();
   950         }
   952 # CONSOLE CHANGE
   953         if ($cl->{"tty"} && $last_tty ne $cl->{"tty"} && 0) {
   954             my $tty = $cl->{"tty"};
   955             $this_day_result .= "         #l3: ------- другая консоль ----\n";
   956             $last_tty=$cl->{"tty"};
   957         }
   959 # Session change
   960         if ( $last_session ne $cl->{"local_session_id"}) {
   961             $this_day_result .= "# ------------------------------------------------------------"
   962                              .  "  l3: local_session_id=".$cl->{"local_session_id"}
   963                              .  " ---------------------------------- \n";
   964             $last_session=$cl->{"local_session_id"};
   965         }
   967 # TIME
   968         my @nl_counter = split (/\n/, $result);
   969         $cursor_position=length($result) - @nl_counter;
   971         if ($Config{"show_time"} =~ /^y/i) {
   972             $this_day_result .= "$hour:$min:$sec" 
   973         }
   975 # COMMAND
   976         $this_day_result .= " ".$cl->{"prompt"}.$cl->{"cline"}."\n";
   977         if ($cl->{"err"}) {
   978             $this_day_result .= "         #l3: err=".$cl->{'err'}."\n";
   979         }
   981 # OUTPUT
   982         my $last_command = $cl->{"last_command"};
   983         if (!( 
   984         $Config{"suppress_editors"} =~ /^y/i && grep ($_ eq $last_command, @{$Config{"editors"}}) ||
   985         $Config{"suppress_pagers"}  =~ /^y/i && grep ($_ eq $last_command, @{$Config{"pagers"}}) ||
   986         $Config{"suppress_terminal"}=~ /^y/i && grep ($_ eq $last_command, @{$Config{"terminal"}})
   987             )) {
   988             my $output = $cl->{short_output};
   989             if ($output) {
   990                  $output =~ s/^/         |/mg;
   991             }
   992             $this_day_result .= $output;
   993         }
   995 # DIFF
   996         if ( $Config{"show_diffs"} =~ /^y/i && $cl->{"diff"}) {
   997             my $diff = $cl->{"diff"};
   998             $diff =~ s/^/         |/mg;
   999             $this_day_result .= $diff;
  1000         };
  1001 # SHOT
  1002         if ($Config{"show_screenshots"} =~ /^y/i && $cl->{"screenshot"}) {
  1003             $this_day_result .= "         #l3: screenshot=".$cl->{'screenshot'}."\n";
  1004         }
  1006 #NOTES
  1007         if ( $Config{"show_notes"} =~ /^y/i && $cl->{"note"}) {
  1008             my $note=$cl->{"note"};
  1009             $note =~ s/\n/\n#^/msg;
  1010             $this_day_result .= "#^ == ".$cl->{note_title}." ==\n" if $cl->{note_title};
  1011             $this_day_result .= "#^ ".$note."\n";
  1012         }
  1014     }
  1015     last: {
  1016         $result .= "== ".$Day_Name[$last_wday]." == \n";
  1017         $result .= $this_day_result;
  1018    }
  1020    return $result;
  1024 }
  1026 #############
  1027 # print_edit_all_html
  1028 #
  1029 # Вывести страницу с текстовым представлением журнала для редактирования
  1030 #
  1031 # In:       $_[0]       output_filename
  1032 # Out:
  1034 sub print_edit_all_html
  1035 {
  1036     my $output_filename= shift;
  1037     my $result;
  1038     my $cursor_position = 0;
  1040     $result = print_command_lines_txt;
  1041     my $title = ">Журнал лабораторных работ. Правка";
  1043     $result = 
  1044                "<html>"
  1045                 ."<head>"
  1046                 ."<meta content='text/html; charset=utf-8' http-equiv='Content-Type' />"
  1047                 ."<link rel='stylesheet' href='$Config{frontend_css}' type='text/css'/>"
  1048                 ."<title>$title</title>"
  1049                 ."</head>"
  1050               ."<script>"
  1051               .$SetCursorPosition_JS
  1052               ."</script>"
  1053               ."<body onLoad='setCursorPosition(document.all.mytextarea, $cursor_position, $cursor_position+10)'>"
  1054               ."<div class='body'>"
  1055               ."<h1>Журнал лабораторных работ. Правка</h1>"
  1056               ."<form>"
  1057               ."<textarea rows='30' cols='100' wrap='off' id='mytextarea'>$result</textarea>"
  1058               ."<br/><input type='submit' value='Сохранить' label='label'/>"
  1059               ."</form>"
  1060               ."<p>Внимательно правим, потом сохраняем</p>"
  1061               ."<p>Строки, начинающиеся символами #l3: можно трогать, только если точно знаешь, что делаешь</p>"
  1062               ."</div>"
  1063               ."</body>"
  1064               ."</html>";
  1066     if ($output_filename eq "-") {
  1067         print $result;
  1068     }
  1069     else {
  1070         open(OUT, ">", $output_filename)
  1071             or die "Can't open $output_filename for writing\n";
  1072         binmode ":utf8";
  1073         print OUT "$result";
  1074         close(OUT);
  1075     }
  1076 }
  1078 #############
  1079 # print_all_txt
  1080 #
  1081 # Вывести страницу с текстовым представлением журнала для редактирования
  1082 #
  1083 # In:       $_[0]       output_filename
  1084 # Out:
  1086 sub print_all_txt
  1087 {
  1088     my $result;
  1090     $result = print_command_lines_txt;
  1092     $result =~ s/>/>/g;
  1093     $result =~ s/</</g;
  1094     $result =~ s/&/&/g;
  1096     if ($output_filename eq "-") {
  1097         print $result;
  1098     }
  1099     else {
  1100         open(OUT, ">:utf8", $output_filename)
  1101             or die "Can't open $output_filename for writing\n";
  1102         print OUT "$result";
  1103         close(OUT);
  1104     }
  1105 }
  1108 #############
  1109 # print_all_html
  1110 #
  1111 #
  1112 #
  1113 # In:       $_[0]       output_filename
  1114 # Out:
  1117 sub print_all_html
  1118 {
  1119     my $output_filename=$_[0];
  1121     my $result;
  1122     my ($command_lines,$toc)  = print_command_lines_html;
  1123     my $files_section         = print_files_html;
  1125     $result = print_header_html($toc);
  1128 #    $result.= join " <br/>", keys %Sessions;
  1129 #    for my $sess (keys %Sessions) {
  1130 #            $result .= join " ", keys (%{$Sessions{$sess}});
  1131 #            $result .= "<br/>";
  1132 #    }
  1134     $result.= "<h2 id='log'>Журнал</h2>"       . $command_lines;
  1135     $result.= "<h2 id='files'>Файлы</h2>"      . $files_section if $files_section;
  1136     $result.= "<h2 id='stat'>Статистика</h2>"  . print_stat_html;
  1137     $result.= "<h2 id='help'>Справка</h2>"     . $Html_Help . "<br/>"; 
  1138     $result.= "<h2 id='about'>О программе</h2>". $Html_About. "<br/>"; 
  1139     $result.= print_footer_html;
  1141     if ($output_filename eq "-") {
  1142         binmode STDOUT, ":utf8";
  1143         print $result;
  1144     }
  1145     else {
  1146         open(OUT, ">:utf8", $output_filename)
  1147             or die "Can't open $output_filename for writing\n";
  1148         print OUT $result;
  1149         close(OUT);
  1150     }
  1151 }
  1153 #############
  1154 # print_header_html
  1155 #
  1156 #
  1157 #
  1158 # In:   $_[0]       Содержание
  1159 # Out:              Распечатанный заголовок
  1161 sub print_header_html
  1162 {
  1163     my $toc = $_[0];
  1164     my $course_name = $Config{"course-name"};
  1165     my $course_code = $Config{"course-code"};
  1166     my $course_date = $Config{"course-date"};
  1167     my $course_center = $Config{"course-center"};
  1168     my $course_trainer = $Config{"course-trainer"};
  1169     my $course_student = $Config{"course-student"};
  1171     my $title    = "Журнал лабораторных работ";
  1172     $title      .= " -- ".$course_student if $course_student;
  1173     if ($course_date) {
  1174         $title  .= " -- ".$course_date; 
  1175         $title  .= $course_code ? "/".$course_code 
  1176                                 : "";
  1177     }
  1178     else {
  1179         $title  .= " -- ".$course_code if $course_code;
  1180     }
  1182     # Управляющая форма
  1183     my $control_form .= "<div class='visibility_form' title='Выберите какие элементы должны быть показаны в журнале'>"
  1184                      .  "<span class='header'>Видимые элементы</span>"
  1185                      .  "<span class='window_controls'><a href='' onclick='' title='свернуть форму управления'>_</a> <a href='' onclick='' title='закрыть форму управления'>x</a></span>"
  1186                      .  "<div><form>\n";
  1187     for my $element (sort keys %Elements_Visibility)
  1188     {
  1189         my ($skip, @e) = split /\s+/, $element;
  1190         my $showhide = join "", map { "ShowHide('$_');" } @e ;
  1191         $control_form .= "<div><input type='checkbox' name='$e[0]' onclick=\"$showhide\" checked>".
  1192                 $Elements_Visibility{$element}.
  1193                 "</input></div>";
  1194     }
  1195     $control_form .= "</form>\n"
  1196                   .  "</div>\n";
  1199     # Управляющая форма отключена
  1200     # Она слишеком сильно мешает, нужно что-то переделать
  1201     $control_form = "";
  1203     my $result;
  1204     $result = <<HEADER;
  1205     <html>
  1206     <head>
  1207     <meta content='text/html; charset=utf-8' http-equiv='Content-Type' />
  1208     <link rel='stylesheet' href='$Config{frontend_css}' type='text/css'/>
  1209     <title>$title</title>
  1210     </head>
  1211     <body>
  1212     <div class='body'>
  1213     <script>
  1214     $Html_JavaScript
  1215     </script>
  1217 <!-- vvv Tigra Hints vvv -->
  1218 <script language="JavaScript" src="/tigra/hints.js"></script>
  1219 <script language="JavaScript" src="/tigra/hints_cfg.js"></script>
  1220 <style>
  1221 /* a class for all Tigra Hints boxes, TD object */
  1222     .hintsClass
  1223         {text-align: center; font-family: Verdana, Arial, Helvetica; padding: 0px 0px 0px 0px;}
  1224 /* this class is used by Tigra Hints wrappers */
  1225     .row
  1226         {background: white;}
  1227 </style>
  1228 <!-- ^^^ Tigra Hints ^^^ -->
  1231     <div class='edit_link'>
  1232     [ <a href='?action=edit&$filter_url'>править</a> ]
  1233     </div>
  1234     <h1 onmouseover="myHint.show('1')" onmouseout="myHint.hide()" class='lined_header'>Журнал лабораторных работ</h1>
  1235 HEADER
  1236     if (    $course_student 
  1237             || $course_trainer 
  1238             || $course_name 
  1239             || $course_code 
  1240             || $course_date 
  1241             || $course_center) {
  1242             $result .= "<p>";
  1243             $result .= "Выполнил $course_student<br/>"  if $course_student;
  1244             $result .= "Проверил $course_trainer <br/>" if $course_trainer;
  1245             $result .= "Курс "                          if $course_name 
  1246                                                             || $course_code 
  1247                                                             || $course_date;
  1248             $result .= "$course_name "                  if $course_name;
  1249             $result .= "($course_code)"                 if $course_code;
  1250             $result .= ", $course_date<br/>"            if $course_date;
  1251             $result .= "Учебный центр $course_center <br/>" if $course_center;
  1252             $result .= "Фильтр ".join(" ", map("$filter{$_}=$_", keys %filter))."<br/>" if %filter;
  1253             $result .= "</p>";
  1254     }
  1256     $result .= <<HEADER;
  1257     <table width='100%'>
  1258     <tr>
  1259     <td width='*'>
  1261     <table border=0 id='toc' class='toc'>
  1262     <tr>
  1263     <td>
  1264     <div class='toc_title'>Содержание</div>
  1265     <ul>
  1266         <li><a href='#log'>Журнал</a></li>
  1267         <ul>$toc</ul>
  1268         <li><a href='#files'>Файлы</a></li>
  1269         <li><a href='#stat'>Статистика</a></li>
  1270         <li><a href='#help'>Справка</a></li>
  1271         <li><a href='#about'>О программе</a></li>
  1272     </ul>
  1273     </td>
  1274     </tr>
  1275     </table>
  1277     </td>
  1278     <td valign='top' width=200>$control_form</td>
  1279     </tr>
  1280     </table>
  1281 HEADER
  1283     return $result;
  1284 }
  1287 #############
  1288 # print_footer_html
  1289 #
  1290 #
  1291 #
  1292 #
  1293 #
  1295 sub print_footer_html
  1296 {
  1297     return "</div></body>\n</html>\n";
  1298 }
  1303 #############
  1304 # print_stat_html
  1305 #
  1306 #
  1307 #
  1308 # In:
  1309 # Out:
  1311 sub print_stat_html
  1312 {
  1313     %StatNames = (
  1314         FirstCommand        => "Время первой команды журнала",
  1315         LastCommand         => "Время последней команды журнала",
  1316         TotalCommands       => "Количество командных строк в журнале",
  1317         ErrorsPercentage    => "Процент команд с ненулевым кодом завершения, %",
  1318         MistypesPercentage  => "Процент синтаксически неверно набранных команд, %",
  1319         TotalTime           => "Суммарное время работы с терминалом <sup><font size='-2'>*</font></sup>, час",
  1320         CommandsPerTime     => "Количество командных строк в единицу времени, команда/мин",
  1321         CommandsFrequency   => "Частота использования команд",
  1322         RareCommands        => "Частота использования этих команд < 0.5%",
  1323     );
  1324     @StatOrder = (
  1325         FirstCommand,
  1326         LastCommand,
  1327         TotalCommands,
  1328         ErrorsPercentage,
  1329         MistypesPercentage,
  1330         TotalTime,
  1331         CommandsPerTime,
  1332         CommandsFrequency,
  1333         RareCommands,
  1334     );
  1336     # Подготовка статистики к выводу
  1337     # Некоторые значения пересчитываются!
  1338     # Дальше их лучше уже не использовать!!!
  1340     my %CommandsFrequency = %frequency_of_command;
  1342     $Stat{TotalTime} ||= 0;
  1343     my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($Stat{FirstCommand} || 0);
  1344     $Stat{FirstCommand} = sprintf "%02i:%02i:%02i %04i-%2i-%2i", $hour, $min, $sec,  $year+1900, $mon+1, $mday;
  1345     ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($Stat{LastCommand} || 0);
  1346     $Stat{LastCommand} = sprintf "%02i:%02i:%02i %04i-%2i-%2i", $hour, $min, $sec,  $year+1900, $mon+1, $mday;
  1347     if ($Stat{TotalCommands}) {
  1348         $Stat{ErrorsPercentage} = sprintf "%5.2f", $Stat{ErrorCommands}*100/$Stat{TotalCommands};
  1349         $Stat{MistypesPercentage} = sprintf "%5.2f", $Stat{MistypedCommands}*100/$Stat{TotalCommands};
  1350     }
  1351     $Stat{CommandsPerTime} = sprintf "%5.2f", $Stat{TotalCommands}*60/$Stat{TotalTime}
  1352         if $Stat{TotalTime};
  1353     $Stat{TotalTime} = sprintf "%5.2f", $Stat{TotalTime}/60/60;
  1355     my $total_commands=0;
  1356     for $command (keys %CommandsFrequency){
  1357         $total_commands += $CommandsFrequency{$command};
  1358     }
  1359     if ($total_commands) {
  1360         for $command (reverse sort {$CommandsFrequency{$a} <=> $CommandsFrequency{$b}} keys %CommandsFrequency){
  1361             my $command_html;
  1362             my $percentage = sprintf "%5.2f",$CommandsFrequency{$command}*100/$total_commands;
  1363             if ($percentage < 0.5) {
  1364                 my $hint = make_comment($command);
  1365                 $command_html = "$command";
  1366                 $command_html = "<span title='$hint' class='with_hint'>$command_html</span>" if $hint;
  1367                 $command_html = "<span class='without_hint'>$command_html</span>" if not $hint;
  1368                 my $command_html = "<tt>$command_html</tt>";
  1369                 $Stat{RareCommands} .= $command_html."<sub><font size='-2'>".$CommandsFrequency{$command}."</font></sub> , ";
  1370             }
  1371             else {
  1372                 my $hint = make_comment($command);
  1373                 $command_html = "$command";
  1374                 $command_html = "<span title='$hint' class='with_hint'>$command_html</span>" if $hint;
  1375                 $command_html = "<span class='without_hint'>$command_html</span>" if not $hint;
  1376                 my $command_html = "<tt>$command_html</tt>";
  1377                 $percentage = sprintf "%5.2f",$percentage;
  1378                 $Stat{CommandsFrequency} .= "<tr><td>".$command_html."</td><td>".$CommandsFrequency{$command}."</td>".
  1379                     "<td>|".("="x int($CommandsFrequency{$command}*100/$total_commands))."| $percentage%</td></tr>";
  1380             }
  1381         }
  1382         $Stat{CommandsFrequency} = "<table>".$Stat{CommandsFrequency}."</table>";
  1383         $Stat{RareCommands} =~ s/, $// if $Stat{RareCommands};
  1384     }
  1386     my $result = q();
  1387     for my $stat (@StatOrder) {
  1388         next unless $Stat{"$stat"};
  1389         $result .= "<tr valign='top'><td width='300'>".$StatNames{"$stat"}."</td><td>".$Stat{"$stat"}."</td></tr>"
  1390     }
  1391     $result  = "<table>$result</table>"
  1392              . "<font size='-2'>____<br/>*) Интервалы неактивности длительностью "
  1393              .  ($Config{stat_inactivity_interval}/60)
  1394              . " минут и более не учитываются</font></br>";
  1396     return $result;
  1397 }
  1400 sub collapse_list($)
  1401 {
  1402     my $res = "";
  1403     for my $elem (@{$_[0]}) {
  1404         if (ref $elem eq "ARRAY") {
  1405             $res .= "<ul>".collapse_list($elem)."</ul>";
  1406         }
  1407         else
  1408         {
  1409             $res .= "<li>".$elem."</li>";
  1410         }
  1411     }
  1412     return $res;
  1413 }
  1416 sub print_files_html
  1417 {
  1418     my $result = qq(); 
  1419     my @toc;
  1420     for my $file (sort keys %Files) {
  1421           my $div_id = "file:$file";
  1422           $div_id =~ s@/@_@g;
  1423           push @toc, "<a href='#$div_id'>$file</a>";
  1424           $result .= "<div class='filename' id='$div_id'>".$file."</div>\n"
  1425                   .  "<div class='file_navigation'><a href='#command:".$Files{$file}->{source_command_id}."'>".">"."</a></div>"
  1426                   .  "<div class='filedata'><pre>".$Files{$file}->{content}."</pre></div>";
  1427     }
  1428     if ($result) {
  1429         return "<div class='files_toc'>".collapse_list(\@toc)."</div>".$result;
  1430     } 
  1431     else {
  1432         return "";
  1433     }
  1434 }
  1437 sub init_variables
  1438 {
  1439 $Html_Help = <<HELP;
  1440     Для того чтобы использовать LiLaLo, не нужно знать ничего особенного:
  1441     всё происходит само собой.
  1442     Однако, чтобы ведение и последующее использование журналов
  1443     было как можно более эффективным, желательно иметь в виду следующее:
  1444     <ol>
  1445     <li><p> 
  1446     В журнал автоматически попадают все команды, данные в любом терминале системы.
  1447     </p></li>
  1448     <li><p>
  1449     Для того чтобы убедиться, что журнал на текущем терминале ведётся, 
  1450     и команды записываются, дайте команду w.
  1451     В поле WHAT, соответствующем текущему терминалу, 
  1452     должна быть указана программа script.
  1453     </p></li>
  1454     <li><p>
  1455     Команды, при наборе которых были допущены синтаксические ошибки, 
  1456     выводятся перечёркнутым текстом:
  1457 <table>
  1458 <tr class='command'>
  1459 <td class='script'>
  1460 <pre class='_mistyped_cline'>
  1461 \$ l s-l</pre>
  1462 <pre class='_mistyped_output'>bash: l: command not found
  1463 </pre>
  1464 </td>
  1465 </tr>
  1466 </table>
  1467 <br/>
  1468     </p></li>
  1469     <li><p>
  1470     Если код завершения команды равен нулю, 
  1471     команда была выполнена без ошибок.
  1472     Команды, код завершения которых отличен от нуля, выделяются цветом.
  1473 <table>
  1474 <tr class='command'>
  1475 <td class='script'>
  1476 <pre class='_wrong_cline'>
  1477 \$ test 5 -lt 4</pre>
  1478 </pre>
  1479 </td>
  1480 </tr>
  1481 </table>
  1482     Обратите внимание на то, что код завершения команды может быть отличен от нуля
  1483     не только в тех случаях, когда команда была выполнена с ошибкой.
  1484     Многие команды используют код завершения, например, для того чтобы показать результаты проверки
  1485 <br/>
  1486     </p></li>
  1487     <li><p>
  1488     Команды, ход выполнения которых был прерван пользователем, выделяются цветом.
  1489 <table>
  1490 <tr class='command'>
  1491 <td class='script'>
  1492 <pre class='_interrupted_cline'>
  1493 \$ find / -name abc</pre>
  1494 <pre class='interrupted_output'>find: /home/devi-orig/.gnome2: Keine Berechtigung
  1495 find: /home/devi-orig/.gnome2_private: Keine Berechtigung
  1496 find: /home/devi-orig/.nautilus/metafiles: Keine Berechtigung
  1497 find: /home/devi-orig/.metacity: Keine Berechtigung
  1498 find: /home/devi-orig/.inkscape: Keine Berechtigung
  1499 ^C
  1500 </pre>
  1501 </td>
  1502 </tr>
  1503 </table>
  1504 <br/>
  1505     </p></li>
  1506     <li><p>
  1507     Команды, выполненные с привилегиями суперпользователя,
  1508     выделяются слева красной чертой.
  1509 <table>
  1510 <tr class='command'>
  1511 <td class='script'>
  1512 <pre class='_root_cline'>
  1513 # id</pre>
  1514 <pre class='_root_output'>
  1515 uid=0(root) gid=0(root) Gruppen=0(root)
  1516 </pre>
  1517 </td>
  1518 </tr>
  1519 </table>
  1520     <br/>
  1521     </p></li>
  1522     <li><p>
  1523     Изменения, внесённые в текстовый файл с помощью редактора, 
  1524     запоминаются и показываются в журнале в формате ed.
  1525     Строки, начинающиеся символом "<", удалены, а строки,
  1526     начинающиеся символом ">" -- добавлены.
  1527 <table>
  1528 <tr class='command'>
  1529 <td class='script'>
  1530 <pre class='cline'>
  1531 \$ vi ~/.bashrc</pre>
  1532 <table><tr><td width='5'/><td class='diff'><pre>2a3,5
  1533 >    if [ -f /usr/local/etc/bash_completion ]; then
  1534 >         . /usr/local/etc/bash_completion
  1535 >        fi
  1536 </pre></td></tr></table></td>
  1537 </tr>
  1538 </table>
  1539     <br/>
  1540     </p></li>
  1541     <li><p>
  1542     Для того чтобы изменить файл в соответствии с показанными в диффшоте
  1543     изменениями, можно воспользоваться командой patch.
  1544     Нужно скопировать изменения, запустить программу patch, указав в
  1545     качестве её аргумента файл, к которому применяются изменения,
  1546     и всавить скопированный текст:
  1547 <table>
  1548 <tr class='command'>
  1549 <td class='script'>
  1550 <pre class='cline'>
  1551 \$ patch ~/.bashrc</pre>
  1552 </td>
  1553 </tr>
  1554 </table>
  1555     В данном случае изменения применяются к файлу ~/.bashrc
  1556     </p></li>
  1557     <li><p>
  1558     Для того чтобы получить краткую справочную информацию о команде, 
  1559     нужно подвести к ней мышь. Во всплывающей подсказке появится краткое
  1560     описание команды.
  1561     </p>
  1562     <p>
  1563     Если справочная информация о команде есть, 
  1564     команда выделяется голубым фоном, например: <span class="with_hint" title="главный текстовый редактор Unix">vi</span>.
  1565     Если справочная информация отсутствует,
  1566     команда выделяется розовым фоном, например: <span class="without_hint">notepad.exe</span>.
  1567     Справочная информация может отсутствовать в том случае, 
  1568     если (1) команда введена неверно; (2) если распознавание команды LiLaLo выполнено неверно;
  1569     (3) если информация о команде неизвестна LiLaLo.
  1570     Последнее возможно для редких команд.
  1571     </p></li>
  1572     <li><p>
  1573     Большие, в особенности многострочные, всплывающие подсказки лучше 
  1574     всего показываются браузерами KDE Konqueror, Apple Safari и Microsoft Internet Explorer.
  1575     В браузерах Mozilla и Firefox они отображаются не полностью, 
  1576     а вместо перевода строки выводится специальный символ.
  1577     </p></li>
  1578     <li><p>
  1579     Время ввода команды, показанное в журнале, соответствует времени 
  1580     <i>начала ввода командной строки</i>, которое равно тому моменту, 
  1581     когда на терминале появилось приглашение интерпретатора
  1582     </p></li>
  1583     <li><p>
  1584     Имя терминала, на котором была введена команда, показано в специальном блоке.
  1585     Этот блок показывается только в том случае, если терминал
  1586     текущей команды отличается от терминала предыдущей.
  1587     </p></li>
  1588     <li><p>
  1589     Вывод не интересующих вас в настоящий момент элементов журнала,
  1590     таких как время, имя терминала и других, можно отключить.
  1591     Для этого нужно воспользоваться <a href='#visibility_form'>формой управления журналом</a>
  1592     вверху страницы.
  1593     </p></li>
  1594     <li><p>
  1595     Небольшие комментарии к командам можно вставлять прямо из командной строки.
  1596     Комментарий вводится прямо в командную строку, после символов #^ или #v.
  1597     Символы ^ и v показывают направление выбора команды, к которой относится комментарий:
  1598     ^ - к предыдущей, v - к следующей.
  1599     Например, если в командной строке было введено:
  1600 <pre class='cline'>
  1601 \$ whoami
  1602 </pre>
  1603 <pre class='output'>
  1604 user
  1605 </pre>
  1606 <pre class='cline'>
  1607 \$ #^ Интересно, кто я?
  1608 </pre>
  1609     в журнале это будет выглядеть так:
  1611 <pre class='cline'>
  1612 \$ whoami
  1613 </pre>
  1614 <pre class='output'>
  1615 user
  1616 </pre>
  1617 <table class='note'><tr><td width='100%' class='note_text'>
  1618 <tr> <td> Интересно, кто я?<br/> </td></tr></table> 
  1619     </p></li>
  1620     <li><p>
  1621     Если комментарий содержит несколько строк,
  1622     его можно вставить в журнал следующим образом:
  1623 <pre class='cline'>
  1624 \$ whoami
  1625 </pre>
  1626 <pre class='output'>
  1627 user
  1628 </pre>
  1629 <pre class='cline'>
  1630 \$ cat > /dev/null #^ Интересно, кто я?
  1631 </pre>
  1632 <pre class='output'>
  1633 Программа whoami выводит имя пользователя, под которым 
  1634 мы зарегистрировались в системе.
  1635 -
  1636 Она не может ответить на вопрос о нашем назначении 
  1637 в этом мире.
  1638 </pre>
  1639     В журнале это будет выглядеть так:
  1640 <table>
  1641 <tr class='command'>
  1642 <td class='script'>
  1643 <pre class='cline'>
  1644 \$ whoami</pre>
  1645 <pre class='output'>user
  1646 </pre>
  1647 <table class='note'><tr><td class='note_title'>Интересно, кто я?</td></tr><tr><td width='100%' class='note_text'>
  1648 Программа whoami выводит имя пользователя, под которым<br/>
  1649 мы зарегистрировались в системе.<br/>
  1650 <br/>
  1651 Она не может ответить на вопрос о нашем назначении<br/>
  1652 в этом мире.<br/>
  1653 </td></tr></table>
  1654 </td>
  1655 </tr>
  1656 </table>
  1657     Для разделения нескольких абзацев между собой
  1658     используйте символ "-", один в строке.
  1659     <br/>
  1660 </p></li>
  1661     <li><p>
  1662     Комментарии, не относящиеся непосредственно ни к какой из команд, 
  1663     добавляются точно таким же способом, только вместо симолов #^ или #v 
  1664     нужно использовать символы #=
  1665     </p></li>
  1667     <p><li>
  1668     Содержимое файла может быть показано в журнале.
  1669     Для этого его нужно вывести с помощью программы cat.
  1670     Если вывод команды отметить симоволами #!, 
  1671     содержимое файла будет показано в журнале
  1672     в специально отведённой для этого секции.
  1673     </li></p>
  1675     <p>
  1676     <li>
  1677     Для того чтобы вставить скриншот интересующего вас окна в журнал,
  1678     нужно воспользоваться командой l3shot.
  1679     После того как команда вызвана, нужно с помощью мыши выбрать окно, которое
  1680     должно быть в журнале.
  1681     </li>
  1682     </p>
  1684     <p>
  1685     <li>
  1686     Команды в журнале расположены в хронологическом порядке.
  1687     Если две команды давались одна за другой, но на разных терминалах,
  1688     в журнале они будут рядом, даже если они не имеют друг к другу никакого отношения.
  1689 <pre>
  1690 1
  1691     2
  1692 3   
  1693     4
  1694 </pre>
  1695     Группы команд, выполненных на разных терминалах, разделяются специальной линией.
  1696     Под этой линией в правом углу показано имя терминала, на котором выполнялись команды.
  1697     Для того чтобы посмотреть команды только одного сенса, 
  1698     нужно щёкнуть по этому названию.
  1699     </li>
  1700     </p>
  1701 </ol>
  1702 HELP
  1704 $Html_About = <<ABOUT;
  1705     <p>
  1706     LiLaLo (L3) расшифровывается как Live Lab Log.<br/>
  1707     Программа разработана для повышения эффективности обучения Unix/Linux-системам.<br/>
  1708     (c) Игорь Чубин, 2004-2006<br/>
  1709     </p>
  1710 ABOUT
  1711 $Html_About.='$Id$ </p>';
  1713 $Html_JavaScript = <<JS;
  1714     function getElementsByClassName(Class_Name)
  1715     {
  1716         var Result=new Array();
  1717         var All_Elements=document.all || document.getElementsByTagName('*');
  1718         for (i=0; i<All_Elements.length; i++)
  1719             if (All_Elements[i].className==Class_Name)
  1720         Result.push(All_Elements[i]);
  1721         return Result;
  1722     }
  1723     function ShowHide (name)
  1724     {
  1725         elements=getElementsByClassName(name);
  1726         for(i=0; i<elements.length; i++)
  1727             if (elements[i].style.display == "none")
  1728                 elements[i].style.display = "";
  1729             else
  1730                 elements[i].style.display = "none";
  1731             //if (elements[i].style.visibility == "hidden")
  1732             //  elements[i].style.visibility = "visible";
  1733             //else
  1734             //  elements[i].style.visibility = "hidden";
  1735     }
  1736     function filter_by_output(text)
  1737     {
  1739         var jjj=0;
  1741         elements=getElementsByClassName('command');
  1742         for(i=0; i<elements.length; i++) {
  1743             subelems = elements[i].getElementsByTagName('pre');
  1744             for(j=0; j<subelems.length; j++) {
  1745                 if (subelems[j].className = 'output') {
  1746                     var str = new String(subelems[j].nodeValue);
  1747                     if (jjj != 1) { 
  1748                         alert(str);
  1749                         jjj=1;
  1750                     }
  1751                     if (str.indexOf(text) >0) 
  1752                         subelems[j].style.display = "none";
  1753                     else
  1754                         subelems[j].style.display = "";
  1756                 }
  1758             }
  1759         }       
  1761     }
  1762 JS
  1764 $SetCursorPosition_JS = <<JS;
  1765 function setCursorPosition(oInput,oStart,oEnd) {
  1766     oInput.focus();
  1767     if( oInput.setSelectionRange ) {
  1768         oInput.setSelectionRange(oStart,oEnd);
  1769     } else if( oInput.createTextRange ) {
  1770         var range = oInput.createTextRange();
  1771         range.collapse(true);
  1772         range.moveEnd('character',oEnd);
  1773         range.moveStart('character',oStart);
  1774         range.select();
  1775     }
  1776 }
  1777 JS
  1779 %Search_Machines = (
  1780         "google" =>     {   "query" =>  "http://www.google.com/search?q=" ,
  1781                     "icon"  =>  "$Config{frontend_google_ico}" },
  1782         "freebsd" =>    {   "query" =>  "http://www.freebsd.org/cgi/man.cgi?query=",
  1783                     "icon"  =>  "$Config{frontend_freebsd_ico}" },
  1784         "linux"  =>     {   "query" =>  "http://man.he.net/?topic=",
  1785                     "icon"  =>  "$Config{frontend_linux_ico}"},
  1786         "opennet"  =>   {   "query" =>  "http://www.opennet.ru/search.shtml?words=",
  1787                     "icon"  =>  "$Config{frontend_opennet_ico}"},
  1788         "local" =>  {   "query" =>  "http://www.freebsd.org/cgi/man.cgi?query=",
  1789                     "icon"  =>  "$Config{frontend_local_ico}" },
  1791     );
  1793 %Elements_Visibility = (
  1794         "0 new_commands_table"      =>  "новые команды",
  1795         "1 diff"      =>  "редактор",
  1796         "2 time"      =>  "время",
  1797         "3 ttychange"     =>  "терминал",
  1798         "4 wrong_output wrong_cline wrong_root_output wrong_root_cline" 
  1799                 =>  "команды с ненулевым кодом завершения",
  1800         "5 mistyped_output mistyped_cline mistyped_root_output mistyped_root_cline" 
  1801                 =>  "неверно набранные команды",
  1802         "6 interrupted_output interrupted_cline interrupted_root_output interrupted_root_cline" 
  1803                 =>  "прерванные команды",
  1804         "7 tab_completion_output tab_completion_cline"    
  1805                 =>  "продолжение с помощью tab"
  1806 );
  1808 @Day_Name      = qw/ Воскресенье Понедельник Вторник Среда Четверг Пятница Суббота /;
  1809 @Month_Name    = qw/ Январь Февраль Март Апрель Май Июнь Июль Август Сентябрь Октябрь Ноябрь Декабрь /;
  1810 @Of_Month_Name = qw/ Января Февраля Марта Апреля Мая Июня Июля Августа Сентября Октября Ноября Декабря /;
  1811 }
  1816 # Временно удалённый код
  1817 # Возможно, он не понадобится уже никогда
  1820 sub search_by
  1821 {
  1822     my $sm = shift;
  1823     my $topic = shift;
  1824     $topic =~ s/ /+/;
  1826     return "<a href='". $Search_Machines{$sm}->{"query"}."$topic'><img width='16' height='16' src='".
  1827                 $Search_Machines{$sm}->{"icon"}."' border='0'/></a>";
  1828 }
