lilalo
view l3-frontend @ 153:0414adc06059
Создана программа l3prompt.c (аналог l3prompt, написанного на Perl).
Занимается тем, что разбивает строку на блоки
и вставляет между ними строки-разделители.
По сути это нужно, чтобы сделать приглашение невидимым.
Сишная версия работает в 2-3 раза быстрее чем перловая.
По умолчанию не инсталлируется.
Для использования нужно откомпилировать
и положить вместо l3prompt
gcc -o l3prompt l3prompt.c
mv l3prompt ~/.lilalo/
Занимается тем, что разбивает строку на блоки
и вставляет между ними строки-разделители.
По сути это нужно, чтобы сделать приглашение невидимым.
Сишная версия работает в 2-3 раза быстрее чем перловая.
По умолчанию не инсталлируется.
Для использования нужно откомпилировать
и положить вместо l3prompt
gcc -o l3prompt l3prompt.c
mv l3prompt ~/.lilalo/
| author | igor@book.xt.vpn | 
|---|---|
| date | Thu Dec 03 12:23:22 2009 +0200 (2009-12-03) | 
| parents | 822b36252d7f | 
| children | 
 line source
     1 #!/usr/bin/perl
     3 use POSIX qw(strftime);
     4 use lib '/etc/lilalo';
     5 use l3config;
     6 use utf8;
     7 no warnings;
     9 our @Command_Lines;
    10 our @Command_Lines_Index;
    11 our %Commands_Description;
    12 our %Args_Description;
    13 our %Sessions;
    14 our %Uploads;
    16 our $debug_output="";      # Используйте эту переменную, если нужно передать отладочную информацию
    18 our %filter;
    19 our $filter_url;
    20 sub init_filter;
    22 our %Files;
    24 # vvv Инициализация переменных выполняется процедурой init_variables
    25 our @Day_Name;
    26 our @Month_Name;
    27 our @Of_Month_Name;
    28 our %Search_Machines;
    29 our %Elements_Visibility;
    30 # ^^^
    32 our $First_Command=$0;
    33 our $Last_Command=40;
    35 our %Stat;
    36 our %frequency_of_command; # Сколько раз в журнале встречается какая команда
    37 our $table_number=1;
    38 our %tigra_hints;
    40 my %mywi_cache_for;         # Кэш для экономии обращений к mywi
    42 sub count_frequency_of_commands;
    43 sub make_comment;
    44 sub make_new_entries_table;
    45 sub load_command_lines_from_xml;
    46 sub load_sessions_from_xml;
    47 sub load_uploads;
    48 sub sort_command_lines;
    49 sub process_command_lines;
    50 sub init_variables;
    51 sub main;
    52 sub collapse_list($);
    54 sub minutes_passed;
    56 sub print_all_txt;
    57 sub print_all_html;
    58 sub print_edit_all_html;
    59 sub print_command_lines_html;
    60 sub print_command_lines_txt;
    61 sub print_files_html;
    62 sub print_stat_html;
    63 sub print_header_html;
    64 sub print_header2_html;
    65 sub print_footer_html;
    66 sub tigra_hints_generate;
    69 #### mywi
    70 # 
    71 sub mywi_init;
    72 sub load_mywitxt;
    73 sub mywi_process_query($);
    74 #
    75 sub add_to_log($$);
    76 sub parse_query;
    77 sub search_in_txt;
    78 sub add_to_log($$);
    79 sub mywi_guess($);
    80 #
    82 main();
    84 sub main
    85 {
    86     $| = 1;
    88     init_variables();
    89     init_config();
    90     $Config{frontend_ico_path}=$Config{frontend_css};
    91     $Config{frontend_ico_path}=~s@/[^/]*$@@;
    92     init_filter();
    93     mywi_init();
    95     load_command_lines_from_xml($Config{"backend_datafile"});
    96     load_uploads($Config{"upload_dir"});
    97     load_sessions_from_xml($Config{"backend_datafile"});
    98     sort_command_lines;
    99     process_command_lines;
   100     if (defined($filter{action}) && $filter{action} eq "edit") {
   101         print_edit_all_html($Config{"output"});
   102     }
   103     else {
   104         print_all_html($Config{"output"});
   105     }
   106 }
   108 sub init_filter
   109 {
   110     if ($Config{filter}) {
   111         # Инициализация фильтра
   112         for (split /;;/,$Config{filter}) {
   113             my ($var, $val) = split /::/;
   114             $filter{$var} = $val || "";
   115         }
   116     }
   117     $filter_url = join (";;", map("$_::$filter{$_}", keys %filter));
   118 }
   120 # extract_from_cline
   122 # In:   $what       = commands | args
   123 # Out:  return      ссылка на хэш, содержащий результаты разбора
   124 #                   команда => позиция
   126 # Разобрать командную строку $_[1] и возвратить хэш, содержащий 
   127 # номер первого появление команды в строке:
   128 #   команда => первая позиция
   129 sub extract_from_cline
   130 {
   131     my $what = $_[0];
   132     my $cline = $_[1];
   133     my @lists = split /\;/, $cline;
   136     my @command_lines = ();
   137     for my $command_list (@lists) {
   138         push(@command_lines, split(/\|/, $command_list));
   139     }
   141     my %position_of_command;
   142     my %position_of_arg;
   143     my $i=0;
   144     for my $command_line (@command_lines) {
   145         $command_line =~ s@^\s*@@;
   146         $command_line =~ /\s*(\S+)\s*(.*)/;
   147         if ($1 && $1 eq "sudo" ) {
   148             $position_of_command{"$1"}=$i++;
   149             $command_line =~ s/\s*sudo\s+//;
   150         }
   151         if ($command_line !~ m@^\s*\S*/etc/@) {
   152             $command_line =~ s@^\s*\S+/@@;
   153         }
   155         $command_line =~ /\s*(\S+)\s*(.*)/;
   156         my $command = $1;
   157         my $args = $2;
   158         if ($command && !defined $position_of_command{"$command"}) {
   159                 $position_of_command{"$command"}=$i++;
   160         };  
   161         if ($args) {
   162             my @args = split (/\s+/, $args);
   163             for my $a (@args) {
   164                 $position_of_arg{"$a"}=$i++
   165                     if !defined $position_of_arg{"$a"};
   166             };  
   167         }
   168     }
   170     if ($what eq "commands") {
   171         return \%position_of_command;
   172     } else {
   173         return \%position_of_arg;
   174     }
   176 }
   178 sub mywrap($)
   179 {
   180 return '<div class="t"><div class="b"><div class="l"><div class="r"><div class="bl"><div class="br"><div class="tl"><div class="tr">'.$_[0].
   181 '</div></div></div></div></div></div></div></div>';
   182 }
   184 sub tigra_hints_generate
   185 {
   186     my $tigra_hints_items="";
   187     for my $hint_id (keys %tigra_hints) {
   188         $tigra_hints{$hint_id} =~ s@\n@<br/>@gs;
   189         $tigra_hints{$hint_id} =~ s@ - @ — @gs;
   190         $tigra_hints{$hint_id} =~ s@'@\\'@gs;
   191 #        $tigra_hints_items .= "'$hint_id' : mywrap('".$tigra_hints{$hint_id}."'),";
   192         $tigra_hints_items .= "'$hint_id' : '".mywrap($tigra_hints{$hint_id})."',";
   193     }
   194     $tigra_hints_items =~ s/,$//; 
   195     return <<TIGRA;
   197 var HINTS_CFG = {
   198 	'top'        : 5, // a vertical offset of a hint from mouse pointer
   199 	'left'       : 5, // a horizontal offset of a hint from mouse pointer
   200 	'css'        : 'hintsClass', // a style class name for all hints, TD object
   201 	'show_delay' : 500, // a delay between object mouseover and hint appearing
   202 	'hide_delay' : 2000, // a delay between hint appearing and hint hiding
   203 	'wise'       : true,
   204 	'follow'     : true,
   205 	'z-index'    : 0 // a z-index for all hint layers
   206 },
   208 HINTS_CFG_NEW = {
   209     'wise'       : true, // don't go off screen, don't overlap the object in the document
   210     'margin'     : 10, // minimum allowed distance between the hint and the window edge (negative values accepted)
   211     'gap'        : 20, // minimum allowed distance between the hint and the origin (negative values accepted)
   212     'align'      : 'bctl', // align of the hint and the origin (by first letters origin's top|middle|bottom left|center|right to hint's top|middle|bottom left|center|right)
   213     'css'        : 'hintsClass', // a style class name for all hints, applied to DIV element (see style section in the header of the document)
   214     'show_delay' : 0, // a delay between initiating event (mouseover for example) and hint appearing
   215     'hide_delay' : 200, // a delay between closing event (mouseout for example) and hint disappearing
   216     'follow'     : true, // hint follows the mouse as it moves
   217     'z-index'    : 100, // a z-index for all hint layers
   218     'IEfix'      : false, // fix IE problem with windowed controls visible through hints (activate if select boxes are visible through the hints)
   219     'IEtrans'    : ['blendTrans(DURATION=.3)', null], // [show transition, hide transition] - nice transition effects, only work in IE5+
   220     'opacity'    : 90 // opacity of the hint in %%
   221 },
   223 HINTS_ITEMS = {
   224     $tigra_hints_items
   225 };
   226 var myHint = new THints (HINTS_CFG, HINTS_ITEMS);
   229 function mywrap (s_) {
   230 return '<div class="t"><div class="b"><div class="l"><div class="r"><div class="bl"><div class="br"><div class="tl"><div class="tr">'+s_+
   231 '</div></div></div></div></div></div></div></div>';
   233 }
   234 TIGRA
   235 $a=<<TIGRA;
   236 TIGRA
   237 }
   240 sub count_frequency_of_commands
   241 {
   242     my $cline = $_[0];
   243     my @commands = keys %{extract_from_cline("commands", $cline)};
   244     for my $command (@commands) {
   245         $frequency_of_command{$command}++;
   246     }
   247 }
   249 sub make_comment
   250 {
   251     my $cline = $_[0];
   252     #my $files = $_[1];
   254     my @comments;
   255     my @commands = keys %{extract_from_cline("commands", $cline)};
   256     my @args = keys %{extract_from_cline("args", $cline)};
   257     return if (!@commands && !@args);
   258     #return "commands=".join(" ",@commands)."; files=".join(" ",@files);
   260     # Commands
   261     for my $command (@commands) {
   262         $command =~ s/'//g;
   263         #$frequency_of_command{$command}++;
   264         if (!$Commands_Description{$command}) {
   265             $mywi_cache_for{$command} ||= mywi_process_query($command) || "";
   266             my $mywi = join ("\n", grep(/\([18]|sh|script\)/, split(/\n/, $mywi_cache_for{$command})));
   267             $mywi =~ s/\s+/ /;
   268             if ($mywi !~ /^\s*$/) {
   269                 $Commands_Description{$command} = $mywi;
   270             }
   271             else {
   272                 next;
   273             }
   274         }
   276         push @comments, $Commands_Description{$command};
   277     }
   278     return join("
\n", @comments);
   280     # Files
   281     for my $arg (@args) {
   282         $arg =~ s/'//g;
   283         if (!$Args_Description{$arg}) {
   284             my $mywi;
   285             $mywi = mywi_client ($arg);
   286             $mywi = join ("\n", grep(/\([5]\)/, split(/\n/, $mywi)));
   287             $mywi =~ s/\s+/ /;
   288             if ($mywi !~ /^\s*$/) {
   289                 $Args_Description{$arg} = $mywi;
   290             }
   291             else {
   292                 next;
   293             }
   294         }
   296         push @comments, $Args_Description{$arg};
   297     }
   299 }
   301 =cut
   302 Процедура load_command_lines_from_xml выполняет загрузку разобранного lab-скрипта
   303 из XML-документа в переменную @Command_Lines
   305 # In:       $datafile           имя файла
   306 # Out:      @CommandLines       загруженные командные строки
   308 Предупреждение!
   309 Процедура не в состоянии обрабатывать XML-документ любой структуры.
   310 В действительности файл cache из которого загружаются данные 
   311 просто напоминает XML с виду.
   312 =cut
   313 sub load_command_lines_from_xml
   314 {
   315     my $datafile = $_[0];
   317     open (CLASS, $datafile)
   318         or die "Can't open file with xml lablog ",$datafile,"\n";
   319     local $/;
   320     binmode CLASS, ":utf8";
   321     $data = <CLASS>;
   322     close(CLASS);
   324     for $command ($data =~ m@<command>(.*?)</command>@sg) {
   325         my %cl;
   326         while ($command =~ m@<([^>]*?)>(.*?)</\1>@sg) {
   327             $cl{$1} = $2;
   328         }
   329         push @Command_Lines, \%cl;
   330     }
   331 }
   333 sub load_sessions_from_xml
   334 {
   335     my $datafile = $_[0];
   337     open (CLASS,  $datafile)
   338         or die "Can't open file with xml lablog ",$datafile,"\n";
   339     local $/;
   340     binmode CLASS, ":utf8";
   341     my $data = <CLASS>;
   342     close(CLASS);
   344     my $i=0;
   345     for my $session ($data =~ m@<session>(.*?)</session>@msg) {
   346         my %session_hash;
   347         while ($session =~ m@<([^>]*?)>(.*?)</\1>@sg) {
   348             $session_hash{$1} = $2;
   349         }
   350         $Sessions{$session_hash{local_session_id}} = \%session_hash;
   351     }
   352 }
   354 sub load_uploads($)
   355 {
   356     $dir=$_[0];
   357     for $i (glob("$dir/*.png")) {
   358       $i =~ s@.*/(([0-9-]+)_([0-9]+).*)@$1@;
   359       if (defined($Uploads{$2}{$3})) {
   360         $Uploads{$2}{$3} .= " ".$i;
   361       }
   362       else {
   363         $Uploads{$2}{$3}=$i;
   364       }
   365     }
   366 }
   368 #for $key (sort keys %session) {
   369 #    for $t (sort { $a <=> $b } keys %{ $session{$key} }) {
   370 #        print $session{$key}{$t}."\n";
   371 #    }
   372 #}
   373 #}
   375 # sort_command_lines
   376 # In:   @Command_Lines
   377 # Out:  @Command_Lies_Index
   379 sub sort_command_lines
   380 {
   382     my @index;
   383     for (my $i=0;$i<=$#Command_Lines;$i++) {
   384         $index[$i]=$i;
   385     }
   387     @Command_Lines_Index = sort {
   388         $Command_Lines[$index[$a]]->{"time"} <=> $Command_Lines[$index[$b]]->{"time"}
   389     } @index;
   391 }
   393 ##################
   394 # process_command_lines
   395 #
   396 # Обрабатываются командные строки @Command_Lines
   397 # Для каждой строки определяется:
   398 #   class   класс    
   399 #   note    комментарий 
   400 #
   401 # In:        @Command_Lines_Index
   402 # In-Out:    @Command_Lines
   404 sub process_command_lines
   405 {
   408     my $current_command=0;
   409     my $prev_i;
   411     my $tab_seq =0 ; # номер команды в последовательности tab-completion
   412                      # отличен от нуля только для тех последовательностей, 
   413                      # где постоянно нажимается клавиша tab
   415 COMMAND_LINE_PROCESSING:
   416     for my $i (@Command_Lines_Index) {
   418         $current_command++;
   419         next if $current_command < $Config{"start_from_command"};
   420         last if $current_command > $Config{"start_from_command"} + $Config{"commands_to_show_at_a_go"};
   422         my $cl = \$Command_Lines[$i];
   425         # Запоминаем предыщуюу команду
   426         # Она нам потребуется, в частности, для ввода tab_seq рпи обработке tab_completion
   427         my $prev_cl;
   428         $prev_cl = \$Command_Lines[$prev_i] if defined($prev_i);
   429         $prev_i = $i;
   431         next if !$cl;
   433         for my $filter_key (keys %filter) {
   434             next COMMAND_LINE_PROCESSING
   435                 if defined($$cl->{local_session_id})
   436                 && defined($Sessions{$$cl->{local_session_id}}->{$filter_key})
   437                 && $Sessions{$$cl->{local_session_id}}->{$filter_key} ne $filter{$filter_key};
   438         }
   440         $$cl->{id} = $$cl->{"time"};
   443         $$cl->{err} ||=0;
   446         # Класс команды
   448         $$cl->{"class"} =   $$cl->{"err"} eq 130 ?  "interrupted"
   449                         :   $$cl->{"err"} eq 127 ?  "mistyped"
   450                         :   $$cl->{"err"}        ?  "wrong"
   451                         :                           "normal";
   453         if ($$cl->{"cline"} && 
   454             $$cl->{"cline"} =~ /[^|`]\s*sudo/
   455             || $$cl->{"uid"} eq 0) {
   456             $$cl->{"class"}.="_root";
   457         }
   459         my $hint;
   460         count_frequency_of_commands($$cl->{"cline"});
   461         $hint = make_comment($$cl->{"cline"});
   463         if ($hint) {
   464             $$cl->{hint} = $hint;
   465         }
   466         $tigra_hints{$$cl->{"time"}} = $hint;
   468         #$$cl->{hint}="";
   470 # Выводим <head_lines> верхних строк
   471 # и <tail_lines> нижних строк,
   472 # если эти параметры существуют
   473         my $output="";
   475         if ($$cl->{"last_command"} eq "cat" && !$$cl->{"err"} && !($$cl->{"cline"} =~ /</)) {
   476             my $filename = $$cl->{"cline"};
   477             $filename =~ s/.*\s+(\S+)\s*$/$1/;
   478             $Files{$filename}->{"content"} = $$cl->{"output"};
   479            $Files{$filename}->{"source_command_id"} = $$cl->{"id"}
   480         }
   481         my @lines = split '\n', $$cl->{"output"};
   482         if ( !$Config{"command_id"} &&
   483              (
   484              $Config{"head_lines"} 
   485              || $Config{"tail_lines"}
   486              )
   487              && $#lines >  $Config{"head_lines"} + $Config{"tail_lines"} ) {
   488 #
   489             for (my $i=0; $i<= $#lines && $i < $Config{"head_lines"}; $i++) {
   490                 $output .= $lines[$i]."\n";
   491             }
   492             $output .= "<a href='?command_id=".$$cl->{id}."'>".$Config{"skip_text"}."</a>\n";
   494             my $start_line=$#lines-$Config{"tail_lines"}+1;
   495             for (my $i=$start_line; $i<= $#lines; $i++) {
   496                 $output .= $lines[$i]."\n";
   497             }
   498         } 
   499         else {
   500            $output = $$cl->{"output"};
   501         }
   502         $$cl->{short_output} = $output;
   504 # Обработка команд с одинаковым временем
   505 # Скорее всего они набраны с помощью tab-completion
   506         if (defined($prev_cl)) {
   507            if ($$prev_cl->{time} == $$cl->{time} && $$prev_cl->{nonce} == $$cl->{nonce}) {
   508             $tab_seq++;
   509            } 
   510            else {
   511             $tab_seq=0;
   512            };
   513            $$prev_cl->{tab_seq}=$tab_seq;
   515 # Обработка команд с одинаковым номером в истории
   516 # Скорее всего они набраны с помощью Ctrl-C
   517            #if ($$prev_cl->{history} == $$cl->{history}) {
   518            # $$prev_cl->{break}=1;
   519            #}
   520         }
   523 #Обработка пометок
   524 #  Если несколько пометок (notes) идут подряд, 
   525 #  они все объединяются
   527         if ($$cl->{cline} =~ /l3shot/) {
   528                 if ($$cl->{output} =~ m@Screenshot is written to.*/(.*)\.xwd@) {
   529                     $$cl->{screenshot}="$1".$Config{l3shot_suffix};
   530                 }
   531         }
   532         if ($$cl->{cline} =~ /l3upload/) {
   533                 if ($$cl->{output} =~ m@Uploaded file name is (.*)@) {
   534                     $$cl->{screenshot}="$1";
   535                 }
   536         }
   538         if ($$cl->{cline}=~ m@cat[^#]*#([\^=v])\s*(.*)@) {
   540             my $note_operator = $1;
   541             my $note_title = $2;
   543             if ($note_operator eq "=") {
   544                 $$cl->{"class"} = "note";
   545                 $$cl->{"note"} = $$cl->{"output"};
   546                 $$cl->{"note_title"} = $2;
   547             }
   548             else {
   549                 my $j = $i;
   550                 if ($note_operator eq "^") {
   551                     $j--;
   552                     $j-- while ($j >=0  && (!$Command_Lines[$j] || $Command_Lines[$j]->{tty} ne $$cl->{tty}));
   553                 }
   554                 elsif ($note_operator eq "v") {
   555                     $j++;
   556                     $j++ while ($j <= @Command_Lines  && (!$Command_Lines[$j] || $Command_Lines[$j]->{tty} ne $$cl->{tty}));
   557                 }
   558                 $Command_Lines[$j]->{note_title}=$note_title;
   559                 $Command_Lines[$j]->{note}.=$$cl->{output};
   560                 $$cl=0;
   561             }
   562         }
   563         elsif ($$cl->{cline}=~ /#([\^=v])(.*)/) {
   565             my $note_operator = $1;
   566             my $note_text = $2;
   568             if ($note_operator eq "=") {
   569                 $$cl->{"class"} = "note";
   570                 $$cl->{"note"} = $note_text;
   571             }
   572             else {
   573                 my $j=$i;
   574                 if ($note_operator eq "^") {
   575                     $j--;
   576                     $j-- while ($j >=0  && (!$Command_Lines[$j] || $Command_Lines[$j]->{tty} ne $$cl->{tty}));
   577                 }
   578                 elsif ($note_operator eq "v") {
   579                     $j++;
   580                     $j++ while ($j <= @Command_Lines  && $Command_Lines[$j]->{tty} ne $$cl->{tty} || !$Command_Lines[$j]);
   581                 }
   582                 $Command_Lines[$j]->{note}.="$note_text\n";
   583                 $$cl=0;
   584             }
   585         }
   586         if ($$cl->{"class"} eq "note") {
   587                 my $note_html = $$cl->{note};
   588                 $note_html = join ("\n", map ("<p>$_</p>", split (/-\n/, $note_html)));
   589                 $note_html =~ s@(http:[a-zA-Z.0-9/?\_%-]*)@<a href='$1'>$1</a>@g;
   590                 $note_html =~ s@(www\.[a-zA-Z.0-9/?\_%-]*)@<a href='$1'>$1</a>@g;
   591                 $$cl->{"note_html"} = $note_html;
   592         }
   593     }   
   595 }
   598 =cut
   599 Процедура print_command_lines выводит HTML-представление
   600 разобранного lab-скрипта. 
   602 Разобранный lab-скрипт должен находиться в массиве @Command_Lines
   603 =cut
   605 sub print_command_lines_html
   606 {
   608     my @toc;                # Оглавление
   609     my $note_number=0;
   611     my $result = q();
   612     my $this_day_resut = q();
   614     my $cl;
   615     my $last_tty="";
   616     my $last_session="";
   617     my $last_day=q();
   618     my $last_wday=q();
   619     my $first_command_of_the_day_unix_time=q();
   620     my $human_readable_time=q();
   621     my $in_range=0;
   623     my $current_command=0;
   625     my @known_commands;
   629     $Stat{LastCommand}   ||= 0;
   630     $Stat{TotalCommands} ||= 0;
   631     $Stat{ErrorCommands} ||= 0;
   632     $Stat{MistypedCommands} ||= 0;
   634     my %new_entries_of = (
   635         "1 1"     =>   "программы пользователя",
   636         "2 8"     =>   "программы администратора",
   637         "3 sh"    =>   "команды интерпретатора",
   638         "4 script"=>   "скрипты",
   639     );
   641 COMMAND_LINE:
   642     for my $k (@Command_Lines_Index) {
   644         my $cl=$Command_Lines[$Command_Lines_Index[$current_command++]];
   645         next unless $cl;
   646         my $next_cl=$Command_Lines[$Command_Lines_Index[$current_command]];
   648         next if $current_command < $Config{"start_from_command"};
   649         last if $current_command > $Config{"start_from_command"} + $Config{"commands_to_show_at_a_go"};
   651         next if $Config{"command_id"} && $cl->{id} ne $Config{"command_id"};
   654 # Пропускаем строки, которые противоречат фильтру
   655 # Если у нас недостаточно информации о том, подходит строка под  фильтр или нет, 
   656 # мы её выводим
   658         for my $filter_key (keys %filter) {
   659             next COMMAND_LINE 
   660                 if defined($cl->{local_session_id})
   661                 && defined($Sessions{$cl->{local_session_id}}->{$filter_key})
   662                 && $Sessions{$cl->{local_session_id}}->{$filter_key} ne $filter{$filter_key};
   663         }
   665 # Набираем статистику
   666 # Хэш %Stat
   668         $Stat{FirstCommand} = $cl->{time} unless $Stat{FirstCommand};
   669         if ($cl->{time} - $Stat{LastCommand} < $Config{stat_inactivity_interval}) {
   670             $Stat{TotalTime} += $cl->{time} - $Stat{LastCommand}
   671         }
   672         my $seconds_since_last_command = $cl->{time} - $Stat{LastCommand};
   674         if ($Stat{LastCommand} > $cl->{time}) {
   675                $result .= "Время идёт вспять<br/>";
   676         };
   677         $Stat{LastCommand} = $cl->{time};
   678         $Stat{TotalCommands}++;
   680 # Пропускаем строки, выходящие за границу "signature",
   681 # при условии, что границы указаны
   682 # Пропускаем неправильные/прерванные/другие команды
   683         if ($Config{"from"} && $cl->{"cline"} =~ /$Config{"signature"}\s*$Config{"from"}/) {
   684             $in_range=1;
   685             next;
   686         }
   687         if ($Config{"to"} && $cl->{"cline"} =~ /$Config{"signature"}\s*$Config{"to"}/) {
   688             $in_range=0;
   689             next;
   690         }
   691         next    if ($Config{"from"} && $Config{"to"}   && !$in_range) 
   692                 || ($Config{"skip_empty"} =~ /^y/i     && $cl->{"cline"} =~ /^\s*$/ )
   693                 || ($Config{"skip_wrong"} =~ /^y/i     && $cl->{"err"} != 0)
   694                 || ($Config{"skip_interrupted"} =~ /^y/i && $cl->{"err"} == 130);
   699 #
   700 ##
   701 ## Начинается собственно вывод
   702 ##
   703 #
   705 ### Сначала обрабатываем границы разделов
   706 ### Если тип команды "note", это граница
   708         if ($cl->{class} eq "note") {
   709             $this_day_result .= "<tr><td colspan='6'>"
   710                              .  "<h4 id='note$note_number'>".$cl->{note_title}."</h4>" if $cl->{note_title}
   711                              .  "".$cl->{note_html}."<p/><p/></td></tr>";
   713             if ($cl->{note_title}) {
   714                 push @{$toc[@toc]},"<a href='#note$note_number'>".$cl->{note_title}."</a>";
   715                 $note_number++;
   716             }
   717             next;
   718         }
   720         my ($sec,$min,$hour,$day,$mon,$year,$wday,$yday,$isdst) = localtime($cl->{time});
   723         # Добавляем спереди 0 для удобочитаемости
   724         $min  = "0".$min  if $min  =~ /^.$/;
   725         $hour = "0".$hour if $hour =~ /^.$/;
   726         $sec  = "0".$sec  if $sec  =~ /^.$/;
   728         $class=$cl->{"class"};
   729         $Stat{ErrorCommands}++          if $class =~ /wrong/;
   730         $Stat{MistypedCommands}++       if $class =~ /mistype/;
   732 # DAY CHANGE
   733         if ( $last_day ne $day) {
   734             $prev_unix_time=$first_command_of_the_day_unix_time;
   735             $first_command_of_the_day_unix_time = $cl->{time};
   736             $human_readable_time = strftime "%D", localtime($prev_unix_time);
   737             if ($last_day) {
   739 # Вычисляем разность множеств.
   740 # Что-то вроде этого, если бы так можно было писать:
   741 #   @new_commands = keys %frequency_of_command - @known_commands;
   744 # Выводим предыдущий день
   746                 $result .= "<h3 id='day_on_sec_$prev_unix_time'>".$Day_Name[$last_wday]." ($human_readable_time)</h3>";
   747                 for my $entry_class (sort keys %new_entries_of) {
   748                     my $table_caption = "Таблица ".$table_number++.".".$Day_Name[$last_wday]
   749                                         .". Новые ".$new_entries_of{$entry_class};
   750                     my $new_commands_section = make_new_entries_table(
   751                                                 $table_caption, 
   752                                                 $entry_class=~/[0-9]+\s+(.*)/, 
   753                                                 \@known_commands);
   754                 }
   755                 @known_commands = keys %frequency_of_command;
   756                 $result .= $this_day_result;
   757             }
   759 # Добавляем текущий день в оглавление
   761             $human_readable_time = strftime "%D", localtime($first_command_of_the_day_unix_time);
   762             push @toc, "<a href='#day_on_sec_$first_command_of_the_day_unix_time'>".$Day_Name[$wday]." ($human_readable_time)</a>\n";
   765             $last_day=$day;
   766             $last_wday=$wday;
   767             $this_day_result = q();
   768         }
   769         else {
   770             $this_day_result .= minutes_passed($seconds_since_last_command);
   771         }
   773         $this_day_result .= "<div class='command' id='command:".$cl->{"id"}."' >\n";
   775 # CONSOLE CHANGE
   776         if ($cl->{"tty"} && $last_tty ne $cl->{"tty"} && 0) {
   777             my $tty = $cl->{"tty"};
   778             $this_day_result .= "<div class='ttychange'>"
   779                                 . $tty
   780                                 ."</div>";
   781             $last_tty=$cl->{"tty"};
   782         }
   784 # Session change
   785         if ( $last_session ne $cl->{"local_session_id"}) {
   786             my $tty;
   787             if (defined $Sessions{$cl->{"local_session_id"}}->{"tty"}) {
   788                 $this_day_result .= "<div class='ttychange'><a href='?filter=local_session_id::".$cl->{"local_session_id"}."'>"
   789                                 . $Sessions{$cl->{"local_session_id"}}->{"tty"}
   790                                 ."</a></div>";
   791             }
   792             $last_session=$cl->{"local_session_id"};
   793         }
   795 # TIME
   796         if ($Config{"show_time"} =~ /^y/i) {
   797             $this_day_result .= "<div class='time'>$hour:$min:$sec</div>" 
   798         }
   800 # COMMAND
   801         my $cline;
   802         $prompt_hint = join ("
", 
   803                          map("$_=$cl->{$_}", 
   804                            grep (!/^(output|short_output|diff)$/, 
   805                              sort(keys(%{$cl})))));
   807         $cl->{"prompt"} =~ s/ $//;
   808         $cline = "<span title='$prompt_hint' class='prompt'><a href='#".$cl->{time}."' id='".$cl->{time}."'>".$cl->{"prompt"}."</a></span>"
   809                 ."<span onmouseover=\"myHint.show('".$cl->{time}."')\" onmouseout=\"myHint.hide()\">".$cl->{"cline"}."</span>";
   810         $cline =~ s/\n//;
   812         if ($cl->{"hint"}) {
   813 #            $cline = "<span title='$cl->{hint}' class='with_hint'>$cline</span>" ;
   814             $cline = "<span class='with_hint'>$cline</span>" ;
   815         } 
   816         else {
   817             $cline = "<span class='without_hint'>$cline</span>";
   818         }
   820         $this_day_result .= "<DIV class='fixed_div'><table cellpadding='0' cellspacing='0'><tr><td>\n<div class='cblock_$cl->{class}'>\n";
   821         $this_day_result .= "<div class='cline'>" . $cline ;      #cline
   822         $this_day_result .= "<span title='Код завершения ".$cl->{"err"}."'>\n"
   823                          .  "<img src='".$Config{frontend_ico_path}."/error.png'/>\n"
   824                          .  "</span>\n" if ($cl->{"err"} and not $cl->{tab_seq} and not $cl->{break});
   825         $this_day_result .= "<span title='Tab completion ".$cl->{tab_seq}."'>\n"
   826                          .  "<img src='".$Config{frontend_ico_path}."/tab.png'/>\n"
   827                          .  "</span>\n" if $cl->{tab_seq};
   828         $this_day_result .= "<span title='Ctrl-C pressed'>\n"
   829                          .  "<img src='".$Config{frontend_ico_path}."/break.png'/>\n"
   830                          .  "</span>\n" if ($cl->{break} and not $cl->{tab_seq});
   831         $this_day_result .= "</div>\n";                             #cline
   833 # OUTPUT
   834         my $last_command = $cl->{"last_command"};
   835         if (!( 
   836         $Config{"suppress_editors"} =~ /^y/i && grep ($_ eq $last_command, @{$Config{"editors"}}) ||
   837         $Config{"suppress_pagers"}  =~ /^y/i && grep ($_ eq $last_command, @{$Config{"pagers"}}) ||
   838         $Config{"suppress_terminal"}=~ /^y/i && grep ($_ eq $last_command, @{$Config{"terminal"}})
   839             )) {
   840             $this_day_result .= "<pre class='output'>\n" . $cl->{short_output} . "</pre>\n";
   841         }
   843 # DIFF
   844         $this_day_result .= "<pre class='diff'>".$cl->{"diff"}."</pre>"
   845             if ( $Config{"show_diffs"} =~ /^y/i && $cl->{"diff"});
   846 # SHOT
   848         #$this_day_result .= join(".", keys(%Uploads));
   849         #$this_day_result .= "PRIVET";
   850         for $t (sort { $a <=> $b } keys %{ $Uploads{$cl->{"local_session_id"}} }) {
   851             if (($t >= $cl->{"time"} and $t < $next_cl->{"time"}) or ($t >= $cl->{"time"} and not defined($next_cl))) {
   852                 my @shots=split(/\s+/, $Uploads{$cl->{"local_session_id"}}{$t});
   853                 for my $shot (@shots) {
   854                     $this_day_result .= "<IMG src='"
   855                         .$Config{l3shot_path}
   856                         .$shot
   857                         ."' alt ='screenshot id ".$shot
   858                         ."'/><br/>"
   859                 }
   860             }
   861         }
   863 # Временно заблокировано
   864 #        $this_day_result .= "<img src='"
   865 #                .$Config{l3shot_path}
   866 #                .$cl->{"screenshot"}
   867 #                ."' alt ='screenshot id ".$cl->{"screenshot"}
   868 #                ."'/>"
   869 #            if ( $Config{"show_screenshots"} =~ /^y/i && $cl->{"screenshot"});
   871 #NOTES
   872         if ( $Config{"show_notes"} =~ /^y/i && $cl->{"note"}) {
   873             my $note=$cl->{"note"};
   874             $note =~ s/\n/<br\/>\n/msg;
   875             if (not $note =~ s@(http:[a-zA-Z.0-9/_?%-]*)@<a href='$1'>$1</a>@g) {
   876               $note =~ s@(www\.[a-zA-Z.0-9/_?%-]*)@<a href='$1'>$1</a>@g;
   877             };
   878             $this_day_result .= "<div class='note'>";
   879             $this_day_result .= "<div class='note_title'>".$cl->{note_title}."</div>" if $cl->{note_title};
   880             $this_day_result .= "<div class='note_text'>".$note."</div>";
   881             $this_day_result .= "</div>\n";
   882         }
   884         # Вывод очередной команды окончен
   885         $this_day_result .= "</div>\n";                     # cblock
   886         $this_day_result .= "</td></tr></table></DIV>\n"
   887                          .  "</div>\n";                     # command
   888     }
   889     last: {
   890         $prev_unix_time=$first_command_of_the_day_unix_time;
   891         $first_command_of_the_day_unix_time = $cl->{time};
   892         $human_readable_time = strftime "%D", localtime($prev_unix_time);
   894         $result .= "<h3 id='day_on_sec_$prev_unix_time'>".$Day_Name[$last_wday]." ($human_readable_time)</h3>";
   896         for my $entry_class (keys %new_entries_of) {
   897             my $table_caption = "Таблица ".$table_number++.".".$Day_Name[$last_wday]
   898                               . ". Новые ".$new_entries_of{$entry_class};
   899             my $new_commands_section = make_new_entries_table(
   900                                         $table_caption, 
   901                                         $entry_class=~/[0-9]+\s+(.*)/, 
   902                                         \@known_commands);
   903         }
   904         @known_commands = keys %frequency_of_command;
   905         $result .= $this_day_result;
   906    }
   908     return ($result, collapse_list (\@toc));
   910 }
   912 #############
   913 # make_new_entries_table
   914 #
   915 # Напечатать таблицу неизвестных команд
   916 #
   917 # In:       $_[0]       table_caption
   918 #           $_[1]       entries_class
   919 #           @_[2..]     known_commands
   920 # Out:
   922 sub make_new_entries_table
   923 {
   924     my $table_caption;
   925     my $entries_class = shift;
   926     my @known_commands = @{$_[0]};
   927     my $result = "";
   929     my %count;
   930     my @new_commands = ();
   931     for my $c (keys %frequency_of_command, @known_commands) {
   932         $count{$c}++
   933     }
   934     for my $c (keys %frequency_of_command) {
   935         push @new_commands, $c if $count{$c} != 2;
   936     }
   938     my $new_commands_section;
   939     if (@new_commands){
   940         my $hint;
   941         for my $c (reverse sort { $frequency_of_command{$a} <=> $frequency_of_command{$b} } @new_commands) {
   942                 $hint = make_comment($c);
   943                 next unless $hint;
   944                 my ($command, $hint) = $hint =~ m/(.*?) \s*- \s*(.*)/;
   945                 next unless $command =~ s/\($entries_class\)//i;
   946                 $new_commands_section .= "<tr><td valign='top'>$command</td><td>$hint</td></tr>";
   947         }
   948     }
   949     if ($new_commands_section) {
   950         $result .= "<table class='new_commands_table' width='700' cellspacing='0' cellpadding='0'>"
   951                 .  "<tr class='new_commands_caption'>"
   952                 .  "<td colspan='2' align='right'>$table_caption</td>"
   953                 .  "</tr>"
   954                 .  "<tr class='new_commands_header'>"
   955                 .  "<td width=100>Команда</td><td width=600>Описание</td>"
   956                 .  "</tr>"
   957                 .  $new_commands_section 
   958                 .  "</table>"
   959     }
   960     return $result;
   961 }
   963 #############
   964 # minutes_passed
   965 #
   966 #
   967 #
   968 # In:       $_[0]       seconds_since_last_command
   969 # Out:                  "minutes passed" text
   971 sub minutes_passed
   972 {
   973         my $seconds_since_last_command = shift;
   974         my $result = "";
   975         if ($seconds_since_last_command > 7200) {
   976             my $hours_passed =  int($seconds_since_last_command/3600);
   977             my $passed_word  = $hours_passed % 10 == 1 ? "прошла"
   978                                                          : "прошло";
   979             my $hours_word   = $hours_passed % 10 == 1 ?   "часа":
   980                                                            "часов";
   981             $result .= "<div class='much_time_passed'>"
   982                     .  $passed_word." >".$hours_passed." ".$hours_word
   983                     .  "</div>\n";
   984         }
   985         elsif ($seconds_since_last_command > 600) {
   986             my $minutes_passed =  int($seconds_since_last_command/60);
   989             my $passed_word  = $minutes_passed % 100 > 10 
   990                             && $minutes_passed % 100 < 20 ? "прошло"
   991                              : $minutes_passed % 10 == 1  ? "прошла"
   992                                                           : "прошло";
   994             my $minutes_word = $minutes_passed % 100 > 10 
   995                             && $minutes_passed % 100 < 20 ? "минут" :
   996                                $minutes_passed % 10 == 1 ? "минута":
   997                                $minutes_passed % 10 == 0 ? "минут" :
   998                                $minutes_passed % 10  > 4 ? "минут" :
   999                                                            "минуты";
  1001             if ($seconds_since_last_command < 1800) {
  1002                 $result .= "<div class='time_passed'>"
  1003                         .  $passed_word." ".$minutes_passed." ".$minutes_word
  1004                         .  "</div>\n";
  1005             }
  1006             else {
  1007                 $result .= "<div class='much_time_passed'>"
  1008                         .  $passed_word." ".$minutes_passed." ".$minutes_word
  1009                         .  "</div>\n";
  1010             }
  1011         }
  1012         return $result;
  1013 }
  1015 #############
  1016 # print_all_txt
  1017 #
  1018 # Вывести журнал в текстовом формате
  1019 #
  1020 # In:       $_[0]       output_filename
  1021 # Out:
  1023 sub print_command_lines_txt
  1024 {
  1026     my $output_filename=$_[0];
  1027     my $note_number=0;
  1029     my $result = q();
  1030     my $this_day_resut = q();
  1032     my $cl;
  1033     my $last_tty="";
  1034     my $last_session="";
  1035     my $last_day=q();
  1036     my $last_wday=q();
  1037     my $in_range=0;
  1039     my $current_command=0;
  1041     my $cursor_position = 0;
  1044     if ($Config{filter}) {
  1045         # Инициализация фильтра
  1046         for (split /&/,$Config{filter}) {
  1047             my ($var, $val) = split /::/;
  1048             $filter{$var} = $val || "";
  1049         }
  1050     }
  1053 COMMAND_LINE:
  1054     for my $k (@Command_Lines_Index) {
  1056         my $cl=$Command_Lines[$Command_Lines_Index[$current_command++]];
  1057         next unless $cl;
  1060 # Пропускаем строки, которые противоречат фильтру
  1061 # Если у нас недостаточно информации о том, подходит строка под  фильтр или нет, 
  1062 # мы её выводим
  1064         for my $filter_key (keys %filter) {
  1065             next COMMAND_LINE 
  1066                 if defined($cl->{local_session_id})
  1067                 && defined($Sessions{$cl->{local_session_id}}->{$filter_key})
  1068                 && $Sessions{$cl->{local_session_id}}->{$filter_key} ne $filter{$filter_key};
  1069         }
  1071 # Пропускаем строки, выходящие за границу "signature",
  1072 # при условии, что границы указаны
  1073 # Пропускаем неправильные/прерванные/другие команды
  1074         if ($Config{"from"} && $cl->{"cline"} =~ /$Config{"signature"}\s*$Config{"from"}/) {
  1075             $in_range=1;
  1076             next;
  1077         }
  1078         if ($Config{"to"} && $cl->{"cline"} =~ /$Config{"signature"}\s*$Config{"to"}/) {
  1079             $in_range=0;
  1080             next;
  1081         }
  1082         next    if ($Config{"from"} && $Config{"to"}   && !$in_range) 
  1083                 || ($Config{"skip_empty"} =~ /^y/i     && $cl->{"cline"} =~ /^\s*$/ )
  1084                 || ($Config{"skip_wrong"} =~ /^y/i     && $cl->{"err"} != 0)
  1085                 || ($Config{"skip_interrupted"} =~ /^y/i && $cl->{"err"} == 130);
  1088 #
  1089 ##
  1090 ## Начинается собственно вывод
  1091 ##
  1092 #
  1094 ### Сначала обрабатываем границы разделов
  1095 ### Если тип команды "note", это граница
  1097         if ($cl->{class} eq "note") {
  1098             $this_day_result .= " === ".$cl->{note_title}." === \n" if $cl->{note_title};
  1099             $this_day_result .= $cl->{note}."\n";
  1100             next;
  1101         }
  1103         my ($sec,$min,$hour,$day,$mon,$year,$wday,$yday,$isdst) = localtime($cl->{time});
  1105         # Добавляем спереди 0 для удобочитаемости
  1106         $min  = "0".$min  if $min  =~ /^.$/;
  1107         $hour = "0".$hour if $hour =~ /^.$/;
  1108         $sec  = "0".$sec  if $sec  =~ /^.$/;
  1110         $class=$cl->{"class"};
  1112 # DAY CHANGE
  1113         if ( $last_day ne $day) {
  1114             if ($last_day) {
  1115                 $result .= "== ".$Day_Name[$last_wday]." == \n";
  1116                 $result .= $this_day_result;
  1117             }
  1118             $last_day   = $day;
  1119             $last_wday  = $wday;
  1120             $this_day_result = q();
  1121         }
  1123 # CONSOLE CHANGE
  1124         if ($cl->{"tty"} && $last_tty ne $cl->{"tty"} && 0) {
  1125             my $tty = $cl->{"tty"};
  1126             $this_day_result .= "         #l3: ------- другая консоль ----\n";
  1127             $last_tty=$cl->{"tty"};
  1128         }
  1130 # Session change
  1131         if ( $last_session ne $cl->{"local_session_id"}) {
  1132             $this_day_result .= "# ------------------------------------------------------------"
  1133                              .  "  l3: local_session_id=".$cl->{"local_session_id"}
  1134                              .  " ---------------------------------- \n";
  1135             $last_session=$cl->{"local_session_id"};
  1136         }
  1138 # TIME
  1139         my @nl_counter = split (/\n/, $result);
  1140         $cursor_position=length($result) - @nl_counter;
  1142         if ($Config{"show_time"} =~ /^y/i) {
  1143             $this_day_result .= "$hour:$min:$sec" 
  1144         }
  1146 # COMMAND
  1147         $this_day_result .= " ".$cl->{"prompt"}.$cl->{"cline"}."\n";
  1148         if ($cl->{"err"}) {
  1149             $this_day_result .= "         #l3: err=".$cl->{'err'}."\n";
  1150         }
  1152 # OUTPUT
  1153         my $last_command = $cl->{"last_command"};
  1154         if (!( 
  1155         $Config{"suppress_editors"} =~ /^y/i && grep ($_ eq $last_command, @{$Config{"editors"}}) ||
  1156         $Config{"suppress_pagers"}  =~ /^y/i && grep ($_ eq $last_command, @{$Config{"pagers"}}) ||
  1157         $Config{"suppress_terminal"}=~ /^y/i && grep ($_ eq $last_command, @{$Config{"terminal"}})
  1158             )) {
  1159             my $output = $cl->{short_output};
  1160             if ($output) {
  1161                  $output =~ s/^/         |/mg;
  1162             }
  1163             $this_day_result .= $output;
  1164         }
  1166 # DIFF
  1167         if ( $Config{"show_diffs"} =~ /^y/i && $cl->{"diff"}) {
  1168             my $diff = $cl->{"diff"};
  1169             $diff =~ s/^/         |/mg;
  1170             $this_day_result .= $diff;
  1171         };
  1172 # SHOT
  1173         if ($Config{"show_screenshots"} =~ /^y/i && $cl->{"screenshot"}) {
  1174             $this_day_result .= "         #l3: screenshot=".$cl->{'screenshot'}."\n";
  1175         }
  1177 #NOTES
  1178         if ( $Config{"show_notes"} =~ /^y/i && $cl->{"note"}) {
  1179             my $note=$cl->{"note"};
  1180             $note =~ s/\n/\n#^/msg;
  1181             $this_day_result .= "#^ == ".$cl->{note_title}." ==\n" if $cl->{note_title};
  1182             $this_day_result .= "#^ ".$note."\n";
  1183         }
  1185     }
  1186     last: {
  1187         $result .= "== ".$Day_Name[$last_wday]." == \n";
  1188         $result .= $this_day_result;
  1189    }
  1191    return $result;
  1195 }
  1197 #############
  1198 # print_edit_all_html
  1199 #
  1200 # Вывести страницу с текстовым представлением журнала для редактирования
  1201 #
  1202 # In:       $_[0]       output_filename
  1203 # Out:
  1205 sub print_edit_all_html
  1206 {
  1207     my $output_filename= shift;
  1208     my $result;
  1209     my $cursor_position = 0;
  1211     $result = print_command_lines_txt;
  1212     my $title = ">Журнал лабораторных работ. Правка";
  1214     $result = 
  1215                "<html>"
  1216                 ."<head>"
  1217                 ."<meta content='text/html; charset=utf-8' http-equiv='Content-Type' />"
  1218                 ."<link rel='stylesheet' href='$Config{frontend_css}' type='text/css'/>"
  1219                 ."<title>$title</title>"
  1220                 ."</head>"
  1221               ."<script>"
  1222               .$SetCursorPosition_JS
  1223               ."</script>"
  1224               ."<body onLoad='setCursorPosition(document.all.mytextarea, $cursor_position, $cursor_position+10)'>"
  1225               ."<h1>Журнал лабораторных работ. Правка</h1>"
  1226               ."<form>"
  1227               ."<textarea rows='30' cols='100' wrap='off' id='mytextarea'>$result</textarea>"
  1228               ."<br/><input type='submit' value='Сохранить' label='label'/>"
  1229               ."</form>"
  1230               ."<p>Внимательно правим, потом сохраняем</p>"
  1231               ."<p>Строки, начинающиеся символами #l3: можно трогать, только если точно знаешь, что делаешь</p>"
  1232               ."</body>"
  1233               ."</html>";
  1235     if ($output_filename eq "-") {
  1236         print $result;
  1237     }
  1238     else {
  1239         open(OUT, ">", $output_filename)
  1240             or die "Can't open $output_filename for writing\n";
  1241         binmode ":utf8";
  1242         print OUT "$result";
  1243         close(OUT);
  1244     }
  1245 }
  1247 #############
  1248 # print_all_txt
  1249 #
  1250 # Вывести страницу с текстовым представлением журнала для редактирования
  1251 #
  1252 # In:       $_[0]       output_filename
  1253 # Out:
  1255 sub print_all_txt
  1256 {
  1257     my $result;
  1259     $result = print_command_lines_txt;
  1261     $result =~ s/>/>/g;
  1262     $result =~ s/</</g;
  1263     $result =~ s/&/&/g;
  1265     if ($output_filename eq "-") {
  1266         print $result;
  1267     }
  1268     else {
  1269         open(OUT, ">:utf8", $output_filename)
  1270             or die "Can't open $output_filename for writing\n";
  1271         print OUT "$result";
  1272         close(OUT);
  1273     }
  1274 }
  1277 #############
  1278 # print_all_html
  1279 #
  1280 #
  1281 #
  1282 # In:       $_[0]       output_filename
  1283 # Out:
  1286 sub print_all_html
  1287 {
  1288     my $output_filename=$_[0];
  1290     my $result;
  1291     my ($command_lines,$toc)  = print_command_lines_html;
  1292     my $files_section         = print_files_html;
  1294     $result = $debug_output;
  1295     $result .= print_header_html($toc);
  1296     if ($Config{"command_id"}) {
  1297         $result .= $command_lines;
  1298     }
  1299     else {
  1300         $result .= print_header2_html($toc);
  1301         $result.= "<h2 id='log'>Журнал</h2>"       . $command_lines;
  1302         $result.= "<h2 id='files'>Файлы</h2>"      . $files_section if $files_section;
  1303         $result.= "<h2 id='stat'>Статистика</h2>"  . print_stat_html;
  1304         $result.= "<h2 id='help'>Справка</h2>"     . $Html_Help . "<br/>"; 
  1305         $result.= "<h2 id='about'>О программе</h2>". $Html_About. "<br/>"; 
  1306     }
  1307     $result.= print_footer_html;
  1309     if ($output_filename eq "-") {
  1310         binmode STDOUT, ":utf8";
  1311         print $result;
  1312     }
  1313     else {
  1314         open(OUT, ">:utf8", $output_filename)
  1315             or die "Can't open $output_filename for writing\n";
  1316         print OUT $result;
  1317         close(OUT);
  1318     }
  1319 }
  1321 #############
  1322 # print_header_html
  1323 #
  1324 #
  1325 #
  1326 # In:   $_[0]       Содержание
  1327 # Out:              Распечатанный заголовок
  1329 sub print_header_html
  1330 {
  1331     my $tigra_hints_array=tigra_hints_generate;
  1333     my $result;
  1334     $result = <<HEADER;
  1335     <html>
  1336     <head>
  1337     <meta content='text/html; charset=utf-8' http-equiv='Content-Type' />
  1338     <link rel='stylesheet' href='$Config{frontend_css}' type='text/css'/>
  1339     <title>$title</title>
  1340     </head>
  1341     <body>
  1342     <!--<script>
  1343     $Html_JavaScript
  1344     </script>-->
  1346 <!-- vvv Tigra Hints vvv -->
  1347 <script language="JavaScript" src="/tigra/hints.js"></script>
  1348 <!--<script language="JavaScript" src="/tigra/hints_cfg.js"></script>-->
  1349 <script>$tigra_hints_array</script>
  1350 <style>
  1351 /* a class for all Tigra Hints boxes, TD object */
  1352     .hintsClass
  1353         {text-align: left; font-size:80%; font-family: Verdana, Arial, Helvetica; background-color:#ffffee; padding: 0px 0px 0px 0px;}
  1354 /* this class is used by Tigra Hints wrappers */
  1355     .row
  1356         {background: white;}
  1359     .bl2 {border: 1px solid #e68200; background:url(/tigra/block/bl2.gif) 0 100% no-repeat; text-align:left}
  1360     .bl {background:url(/tigra/block/bl2.gif) 0 100% no-repeat; text-align:left}
  1361     .br {background:url(/tigra/block/br2.gif) 100% 100% no-repeat}
  1362     .tl {background:url(/tigra/block/tl2.gif) 0 0 no-repeat}
  1363     .tr {background:url(/tigra/block/tr2.gif) 100% 0 no-repeat; padding:10px}
  1364     .tr2 {background:url(/tigra/block/tr2.gif) 100% 0 no-repeat}
  1365     .t {background:url(/tigra/block/dot2.gif) 0 0 repeat-x}
  1366     .b {background:url(/tigra/block/dot2.gif) 0 100% repeat-x}
  1367     .l {background:url(/tigra/block/dot2.gif) 0 0 repeat-y}
  1368     .r {background:url(/tigra/block/dot2.gif) 100% 0 repeat-y}
  1371 </style>
  1372 <!-- ^^^ Tigra Hints ^^^ -->
  1373 HEADER
  1374     return $result;
  1375 }
  1377 sub print_header2_html
  1378 {
  1379     my $result ="";
  1380     my $toc = $_[0];
  1381     my $course_name = $Config{"course-name"};
  1382     my $course_code = $Config{"course-code"};
  1383     my $course_date = $Config{"course-date"};
  1384     my $course_center = $Config{"course-center"};
  1385     my $course_trainer = $Config{"course-trainer"};
  1386     my $course_student = $Config{"course-student"};
  1388     my $title    = "Журнал лабораторных работ";
  1389     $title      .= " -- ".$course_student if $course_student;
  1390     if ($course_date) {
  1391         $title  .= " -- ".$course_date; 
  1392         $title  .= $course_code ? "/".$course_code 
  1393                                 : "";
  1394     }
  1395     else {
  1396         $title  .= " -- ".$course_code if $course_code;
  1397     }
  1399     # Управляющая форма
  1400     my $control_form .= "<div class='visibility_form' title='Выберите какие элементы должны быть показаны в журнале'>"
  1401                      .  "<span class='header'>Видимые элементы</span>"
  1402                      .  "<span class='window_controls'><a href='' onclick='' title='свернуть форму управления'>_</a> <a href='' onclick='' title='закрыть форму управления'>x</a></span>"
  1403                      .  "<div><form>\n";
  1404     for my $element (sort keys %Elements_Visibility)
  1405     {
  1406         my ($skip, @e) = split /\s+/, $element;
  1407         my $showhide = join "", map { "ShowHide('$_');" } @e ;
  1408         $control_form .= "<div><input type='checkbox' name='$e[0]' onclick=\"$showhide\" checked>".
  1409                 $Elements_Visibility{$element}.
  1410                 "</input></div>";
  1411     }
  1412     $control_form .= "</form>\n"
  1413                   .  "</div>\n";
  1416     # Управляющая форма отключена
  1417     # Она слишком сильно мешает, нужно что-то переделать
  1418     $control_form = "";
  1421     $result .= <<HEADER;
  1422     <div class='edit_link'>
  1423     [ <a href='?filter=action::edit;;$filter_url'>править</a> ]
  1424     </div>
  1425     <h1 onmouseover="myHint.show('1')" onmouseout="myHint.hide()" class='lined_header'>Журнал лабораторных работ</h1>
  1426 HEADER
  1427     if (    $course_student 
  1428             || $course_trainer 
  1429             || $course_name 
  1430             || $course_code 
  1431             || $course_date 
  1432             || $course_center) {
  1433             $result .= "<p>";
  1434             $result .= "Выполнил $course_student<br/>"  if $course_student;
  1435             $result .= "Проверил $course_trainer <br/>" if $course_trainer;
  1436             $result .= "Курс "                          if $course_name 
  1437                                                             || $course_code 
  1438                                                             || $course_date;
  1439             $result .= "$course_name "                  if $course_name;
  1440             $result .= "($course_code)"                 if $course_code;
  1441             $result .= ", $course_date<br/>"            if $course_date;
  1442             $result .= "Учебный центр $course_center <br/>" if $course_center;
  1443             $result .= "Фильтр ".join(" ", map("$filter{$_}=$_", keys %filter))."<br/>" if %filter;
  1444             $result .= "</p>";
  1445     }
  1447     $result .= <<HEADER;
  1448     <table width='100%'>
  1449     <tr>
  1450     <td width='*'>
  1452     <table border=0 id='toc' class='toc'>
  1453     <tr>
  1454     <td>
  1455     <div class='toc_title'>Содержание</div>
  1456     <ul>
  1457         <li><a href='#log'>Журнал</a></li>
  1458         <ul>$toc</ul>
  1459         <li><a href='#files'>Файлы</a></li>
  1460         <li><a href='#stat'>Статистика</a></li>
  1461         <li><a href='#help'>Справка</a></li>
  1462         <li><a href='#about'>О программе</a></li>
  1463     </ul>
  1464     </td>
  1465     </tr>
  1466     </table>
  1468     </td>
  1469     <td valign='top' width=200>$control_form</td>
  1470     </tr>
  1471     </table>
  1472 HEADER
  1474     return $result;
  1475 }
  1478 #############
  1479 # print_footer_html
  1480 #
  1481 #
  1482 #
  1483 #
  1484 #
  1486 sub print_footer_html
  1487 {
  1488     return "</body>\n</html>\n";
  1489 }
  1494 #############
  1495 # print_stat_html
  1496 #
  1497 #
  1498 #
  1499 # In:
  1500 # Out:
  1502 sub print_stat_html
  1503 {
  1504     %StatNames = (
  1505         FirstCommand        => "Время первой команды журнала",
  1506         LastCommand         => "Время последней команды журнала",
  1507         TotalCommands       => "Количество командных строк в журнале",
  1508         ErrorsPercentage    => "Процент команд с ненулевым кодом завершения, %",
  1509         MistypesPercentage  => "Процент синтаксически неверно набранных команд, %",
  1510         TotalTime           => "Суммарное время работы с терминалом <sup><font size='-2'>*</font></sup>, час",
  1511         CommandsPerTime     => "Количество командных строк в единицу времени, команда/мин",
  1512         CommandsFrequency   => "Частота использования команд",
  1513         RareCommands        => "Частота использования этих команд < 0.5%",
  1514     );
  1515     @StatOrder = (
  1516         FirstCommand,
  1517         LastCommand,
  1518         TotalCommands,
  1519         ErrorsPercentage,
  1520         MistypesPercentage,
  1521         TotalTime,
  1522         CommandsPerTime,
  1523         CommandsFrequency,
  1524         RareCommands,
  1525     );
  1527     # Подготовка статистики к выводу
  1528     # Некоторые значения пересчитываются!
  1529     # Дальше их лучше уже не использовать!!!
  1531     my %CommandsFrequency = %frequency_of_command;
  1533     $Stat{TotalTime} ||= 0;
  1534     my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($Stat{FirstCommand} || 0);
  1535     $Stat{FirstCommand} = sprintf "%02i:%02i:%02i %04i-%2i-%2i", $hour, $min, $sec,  $year+1900, $mon+1, $mday;
  1536     ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($Stat{LastCommand} || 0);
  1537     $Stat{LastCommand} = sprintf "%02i:%02i:%02i %04i-%2i-%2i", $hour, $min, $sec,  $year+1900, $mon+1, $mday;
  1538     if ($Stat{TotalCommands}) {
  1539         $Stat{ErrorsPercentage} = sprintf "%5.2f", $Stat{ErrorCommands}*100/$Stat{TotalCommands};
  1540         $Stat{MistypesPercentage} = sprintf "%5.2f", $Stat{MistypedCommands}*100/$Stat{TotalCommands};
  1541     }
  1542     $Stat{CommandsPerTime} = sprintf "%5.2f", $Stat{TotalCommands}*60/$Stat{TotalTime}
  1543         if $Stat{TotalTime};
  1544     $Stat{TotalTime} = sprintf "%5.2f", $Stat{TotalTime}/60/60;
  1546     my $total_commands=0;
  1547     for $command (keys %CommandsFrequency){
  1548         $total_commands += $CommandsFrequency{$command};
  1549     }
  1550     if ($total_commands) {
  1551         for $command (reverse sort {$CommandsFrequency{$a} <=> $CommandsFrequency{$b}} keys %CommandsFrequency){
  1552             my $command_html;
  1553             my $percentage = sprintf "%5.2f",$CommandsFrequency{$command}*100/$total_commands;
  1554             if ($percentage < 0.5) {
  1555                 my $hint = make_comment($command);
  1556                 $command_html = "$command";
  1557                 $command_html = "<span title='$hint' class='with_hint'>$command_html</span>" if $hint;
  1558                 $command_html = "<span class='without_hint'>$command_html</span>" if not $hint;
  1559                 my $command_html = "<tt>$command_html</tt>";
  1560                 $Stat{RareCommands} .= $command_html."<sub><font size='-2'>".$CommandsFrequency{$command}."</font></sub> , ";
  1561             }
  1562             else {
  1563                 my $hint = make_comment($command);
  1564                 $command_html = "$command";
  1565                 $command_html = "<span title='$hint' class='with_hint'>$command_html</span>" if $hint;
  1566                 $command_html = "<span class='without_hint'>$command_html</span>" if not $hint;
  1567                 my $command_html = "<tt>$command_html</tt>";
  1568                 $percentage = sprintf "%5.2f",$percentage;
  1569                 $Stat{CommandsFrequency} .= "<tr><td>".$command_html."</td><td>".$CommandsFrequency{$command}."</td>".
  1570                     "<td>|".("="x int($CommandsFrequency{$command}*100/$total_commands))."| $percentage%</td></tr>";
  1571             }
  1572         }
  1573         $Stat{CommandsFrequency} = "<table>".$Stat{CommandsFrequency}."</table>";
  1574         $Stat{RareCommands} =~ s/, $// if $Stat{RareCommands};
  1575     }
  1577     my $result = q();
  1578     for my $stat (@StatOrder) {
  1579         next unless $Stat{"$stat"};
  1580         $result .= "<tr valign='top'><td width='300'>".$StatNames{"$stat"}."</td><td>".$Stat{"$stat"}."</td></tr>"
  1581     }
  1582     $result  = "<table>$result</table>"
  1583              . "<font size='-2'>____<br/>*) Интервалы неактивности длительностью "
  1584              .  ($Config{stat_inactivity_interval}/60)
  1585              . " минут и более не учитываются</font></br>";
  1587     return $result;
  1588 }
  1591 sub collapse_list($)
  1592 {
  1593     my $res = "";
  1594     for my $elem (@{$_[0]}) {
  1595         if (ref $elem eq "ARRAY") {
  1596             $res .= "<ul>".collapse_list($elem)."</ul>";
  1597         }
  1598         else
  1599         {
  1600             $res .= "<li>".$elem."</li>";
  1601         }
  1602     }
  1603     return $res;
  1604 }
  1607 sub print_files_html
  1608 {
  1609     my $result = qq(); 
  1610     my @toc;
  1611     for my $file (sort keys %Files) {
  1612           my $div_id = "file:$file";
  1613           $div_id =~ s@/@_@g;
  1614           push @toc, "<a href='#$div_id'>$file</a>";
  1615           $result .= "<div class='filename' id='$div_id'>".$file."</div>\n"
  1616                   .  "<div class='file_navigation'><a href='#command:".$Files{$file}->{source_command_id}."'>".">"."</a></div>"
  1617                   .  "<div class='filedata'><pre>".$Files{$file}->{content}."</pre></div>";
  1618     }
  1619     if ($result) {
  1620         return "<div class='files_toc'>".collapse_list(\@toc)."</div>".$result;
  1621     } 
  1622     else {
  1623         return "";
  1624     }
  1625 }
  1628 sub init_variables
  1629 {
  1630 $Html_Help = <<HELP;
  1631     Для того чтобы использовать LiLaLo, не нужно знать ничего особенного:
  1632     всё происходит само собой.
  1633     Однако, чтобы ведение и последующее использование журналов
  1634     было как можно более эффективным, желательно иметь в виду следующее:
  1635     <ol>
  1636     <li><p> 
  1637     В журнал автоматически попадают все команды, данные в любом терминале системы.
  1638     </p></li>
  1639     <li><p>
  1640     Для того чтобы убедиться, что журнал на текущем терминале ведётся, 
  1641     и команды записываются, дайте команду w.
  1642     В поле WHAT, соответствующем текущему терминалу, 
  1643     должна быть указана программа script.
  1644     </p></li>
  1645     <li><p>
  1646     Команды, при наборе которых были допущены синтаксические ошибки, 
  1647     выводятся перечёркнутым текстом:
  1648 <table>
  1649 <tr class='command'>
  1650 <td class='script'>
  1651 <pre class='_mistyped_cline'>
  1652 \$ l s-l</pre>
  1653 <pre class='_mistyped_output'>bash: l: command not found
  1654 </pre>
  1655 </td>
  1656 </tr>
  1657 </table>
  1658 <br/>
  1659     </p></li>
  1660     <li><p>
  1661     Если код завершения команды равен нулю, 
  1662     команда была выполнена без ошибок.
  1663     Команды, код завершения которых отличен от нуля, выделяются цветом.
  1664 <table>
  1665 <tr class='command'>
  1666 <td class='script'>
  1667 <pre class='_wrong_cline'>
  1668 \$ test 5 -lt 4</pre>
  1669 </pre>
  1670 </td>
  1671 </tr>
  1672 </table>
  1673     Обратите внимание на то, что код завершения команды может быть отличен от нуля
  1674     не только в тех случаях, когда команда была выполнена с ошибкой.
  1675     Многие команды используют код завершения, например, для того чтобы показать результаты проверки
  1676 <br/>
  1677     </p></li>
  1678     <li><p>
  1679     Команды, ход выполнения которых был прерван пользователем, выделяются цветом.
  1680 <table>
  1681 <tr class='command'>
  1682 <td class='script'>
  1683 <pre class='_interrupted_cline'>
  1684 \$ find / -name abc</pre>
  1685 <pre class='interrupted_output'>find: /home/devi-orig/.gnome2: Keine Berechtigung
  1686 find: /home/devi-orig/.gnome2_private: Keine Berechtigung
  1687 find: /home/devi-orig/.nautilus/metafiles: Keine Berechtigung
  1688 find: /home/devi-orig/.metacity: Keine Berechtigung
  1689 find: /home/devi-orig/.inkscape: Keine Berechtigung
  1690 ^C
  1691 </pre>
  1692 </td>
  1693 </tr>
  1694 </table>
  1695 <br/>
  1696     </p></li>
  1697     <li><p>
  1698     Команды, выполненные с привилегиями суперпользователя,
  1699     выделяются слева красной чертой.
  1700 <table>
  1701 <tr class='command'>
  1702 <td class='script'>
  1703 <pre class='_root_cline'>
  1704 # id</pre>
  1705 <pre class='_root_output'>
  1706 uid=0(root) gid=0(root) Gruppen=0(root)
  1707 </pre>
  1708 </td>
  1709 </tr>
  1710 </table>
  1711     <br/>
  1712     </p></li>
  1713     <li><p>
  1714     Изменения, внесённые в текстовый файл с помощью редактора, 
  1715     запоминаются и показываются в журнале в формате ed.
  1716     Строки, начинающиеся символом "<", удалены, а строки,
  1717     начинающиеся символом ">" -- добавлены.
  1718 <table>
  1719 <tr class='command'>
  1720 <td class='script'>
  1721 <pre class='cline'>
  1722 \$ vi ~/.bashrc</pre>
  1723 <table><tr><td width='5'/><td class='diff'><pre>2a3,5
  1724 >    if [ -f /usr/local/etc/bash_completion ]; then
  1725 >         . /usr/local/etc/bash_completion
  1726 >        fi
  1727 </pre></td></tr></table></td>
  1728 </tr>
  1729 </table>
  1730     <br/>
  1731     </p></li>
  1732     <li><p>
  1733     Для того чтобы изменить файл в соответствии с показанными в диффшоте
  1734     изменениями, можно воспользоваться командой patch.
  1735     Нужно скопировать изменения, запустить программу patch, указав в
  1736     качестве её аргумента файл, к которому применяются изменения,
  1737     и всавить скопированный текст:
  1738 <table>
  1739 <tr class='command'>
  1740 <td class='script'>
  1741 <pre class='cline'>
  1742 \$ patch ~/.bashrc</pre>
  1743 </td>
  1744 </tr>
  1745 </table>
  1746     В данном случае изменения применяются к файлу ~/.bashrc
  1747     </p></li>
  1748     <li><p>
  1749     Для того чтобы получить краткую справочную информацию о команде, 
  1750     нужно подвести к ней мышь. Во всплывающей подсказке появится краткое
  1751     описание команды.
  1752     </p>
  1753     <p>
  1754     Если справочная информация о команде есть, 
  1755     команда выделяется голубым фоном, например: <span class="with_hint" title="главный текстовый редактор Unix">vi</span>.
  1756     Если справочная информация отсутствует,
  1757     команда выделяется розовым фоном, например: <span class="without_hint">notepad.exe</span>.
  1758     Справочная информация может отсутствовать в том случае, 
  1759     если (1) команда введена неверно; (2) если распознавание команды LiLaLo выполнено неверно;
  1760     (3) если информация о команде неизвестна LiLaLo.
  1761     Последнее возможно для редких команд.
  1762     </p></li>
  1763     <li><p>
  1764     Большие, в особенности многострочные, всплывающие подсказки лучше 
  1765     всего показываются браузерами KDE Konqueror, Apple Safari и Microsoft Internet Explorer.
  1766     В браузерах Mozilla и Firefox они отображаются не полностью, 
  1767     а вместо перевода строки выводится специальный символ.
  1768     </p></li>
  1769     <li><p>
  1770     Время ввода команды, показанное в журнале, соответствует времени 
  1771     <i>начала ввода командной строки</i>, которое равно тому моменту, 
  1772     когда на терминале появилось приглашение интерпретатора
  1773     </p></li>
  1774     <li><p>
  1775     Имя терминала, на котором была введена команда, показано в специальном блоке.
  1776     Этот блок показывается только в том случае, если терминал
  1777     текущей команды отличается от терминала предыдущей.
  1778     </p></li>
  1779     <li><p>
  1780     Вывод не интересующих вас в настоящий момент элементов журнала,
  1781     таких как время, имя терминала и других, можно отключить.
  1782     Для этого нужно воспользоваться <a href='#visibility_form'>формой управления журналом</a>
  1783     вверху страницы.
  1784     </p></li>
  1785     <li><p>
  1786     Небольшие комментарии к командам можно вставлять прямо из командной строки.
  1787     Комментарий вводится прямо в командную строку, после символов #^ или #v.
  1788     Символы ^ и v показывают направление выбора команды, к которой относится комментарий:
  1789     ^ - к предыдущей, v - к следующей.
  1790     Например, если в командной строке было введено:
  1791 <pre class='cline'>
  1792 \$ whoami
  1793 </pre>
  1794 <pre class='output'>
  1795 user
  1796 </pre>
  1797 <pre class='cline'>
  1798 \$ #^ Интересно, кто я?
  1799 </pre>
  1800     в журнале это будет выглядеть так:
  1802 <pre class='cline'>
  1803 \$ whoami
  1804 </pre>
  1805 <pre class='output'>
  1806 user
  1807 </pre>
  1808 <table class='note'><tr><td width='100%' class='note_text'>
  1809 <tr> <td> Интересно, кто я?<br/> </td></tr></table> 
  1810     </p></li>
  1811     <li><p>
  1812     Если комментарий содержит несколько строк,
  1813     его можно вставить в журнал следующим образом:
  1814 <pre class='cline'>
  1815 \$ whoami
  1816 </pre>
  1817 <pre class='output'>
  1818 user
  1819 </pre>
  1820 <pre class='cline'>
  1821 \$ cat > /dev/null #^ Интересно, кто я?
  1822 </pre>
  1823 <pre class='output'>
  1824 Программа whoami выводит имя пользователя, под которым 
  1825 мы зарегистрировались в системе.
  1826 -
  1827 Она не может ответить на вопрос о нашем назначении 
  1828 в этом мире.
  1829 </pre>
  1830     В журнале это будет выглядеть так:
  1831 <table>
  1832 <tr class='command'>
  1833 <td class='script'>
  1834 <pre class='cline'>
  1835 \$ whoami</pre>
  1836 <pre class='output'>user
  1837 </pre>
  1838 <table class='note'><tr><td class='note_title'>Интересно, кто я?</td></tr><tr><td width='100%' class='note_text'>
  1839 Программа whoami выводит имя пользователя, под которым<br/>
  1840 мы зарегистрировались в системе.<br/>
  1841 <br/>
  1842 Она не может ответить на вопрос о нашем назначении<br/>
  1843 в этом мире.<br/>
  1844 </td></tr></table>
  1845 </td>
  1846 </tr>
  1847 </table>
  1848     Для разделения нескольких абзацев между собой
  1849     используйте символ "-", один в строке.
  1850     <br/>
  1851 </p></li>
  1852     <li><p>
  1853     Комментарии, не относящиеся непосредственно ни к какой из команд, 
  1854     добавляются точно таким же способом, только вместо симолов #^ или #v 
  1855     нужно использовать символы #=
  1856     </p></li>
  1858     <p><li>
  1859     Содержимое файла может быть показано в журнале.
  1860     Для этого его нужно вывести с помощью программы cat.
  1861     Если вывод команды отметить симоволами #!, 
  1862     содержимое файла будет показано в журнале
  1863     в специально отведённой для этого секции.
  1864     </li></p>
  1866     <p>
  1867     <li>
  1868     Для того чтобы вставить скриншот интересующего вас окна в журнал,
  1869     нужно воспользоваться командой l3shot.
  1870     После того как команда вызвана, нужно с помощью мыши выбрать окно, которое
  1871     должно быть в журнале.
  1872     </li>
  1873     </p>
  1875     <p>
  1876     <li>
  1877     Команды в журнале расположены в хронологическом порядке.
  1878     Если две команды давались одна за другой, но на разных терминалах,
  1879     в журнале они будут рядом, даже если они не имеют друг к другу никакого отношения.
  1880 <pre>
  1881 1
  1882     2
  1883 3   
  1884     4
  1885 </pre>
  1886     Группы команд, выполненных на разных терминалах, разделяются специальной линией.
  1887     Под этой линией в правом углу показано имя терминала, на котором выполнялись команды.
  1888     Для того чтобы посмотреть команды только одного сенса, 
  1889     нужно щёкнуть по этому названию.
  1890     </li>
  1891     </p>
  1892 </ol>
  1893 HELP
  1895 $Html_About = <<ABOUT;
  1896     <p>
  1897     <a href='http://xgu.ru/lilalo/'>LiLaLo</a> (L3) расшифровывается как Live Lab Log.<br/>
  1898     Программа разработана для повышения эффективности обучения Unix/Linux-системам.<br/>
  1899     (c) Игорь Чубин, 2004-2008<br/>
  1900     </p>
  1901 ABOUT
  1902 $Html_About.='$Id$ </p>';
  1904 $Html_JavaScript = <<JS;
  1905     function getElementsByClassName(Class_Name)
  1906     {
  1907         var Result=new Array();
  1908         var All_Elements=document.all || document.getElementsByTagName('*');
  1909         for (i=0; i<All_Elements.length; i++)
  1910             if (All_Elements[i].className==Class_Name)
  1911         Result.push(All_Elements[i]);
  1912         return Result;
  1913     }
  1914     function ShowHide (name)
  1915     {
  1916         elements=getElementsByClassName(name);
  1917         for(i=0; i<elements.length; i++)
  1918             if (elements[i].style.display == "none")
  1919                 elements[i].style.display = "";
  1920             else
  1921                 elements[i].style.display = "none";
  1922             //if (elements[i].style.visibility == "hidden")
  1923             //  elements[i].style.visibility = "visible";
  1924             //else
  1925             //  elements[i].style.visibility = "hidden";
  1926     }
  1927     function filter_by_output(text)
  1928     {
  1930         var jjj=0;
  1932         elements=getElementsByClassName('command');
  1933         for(i=0; i<elements.length; i++) {
  1934             subelems = elements[i].getElementsByTagName('pre');
  1935             for(j=0; j<subelems.length; j++) {
  1936                 if (subelems[j].className = 'output') {
  1937                     var str = new String(subelems[j].nodeValue);
  1938                     if (jjj != 1) { 
  1939                         alert(str);
  1940                         jjj=1;
  1941                     }
  1942                     if (str.indexOf(text) >0) 
  1943                         subelems[j].style.display = "none";
  1944                     else
  1945                         subelems[j].style.display = "";
  1947                 }
  1949             }
  1950         }       
  1952     }
  1953 JS
  1955 $SetCursorPosition_JS = <<JS;
  1956 function setCursorPosition(oInput,oStart,oEnd) {
  1957     oInput.focus();
  1958     if( oInput.setSelectionRange ) {
  1959         oInput.setSelectionRange(oStart,oEnd);
  1960     } else if( oInput.createTextRange ) {
  1961         var range = oInput.createTextRange();
  1962         range.collapse(true);
  1963         range.moveEnd('character',oEnd);
  1964         range.moveStart('character',oStart);
  1965         range.select();
  1966     }
  1967 }
  1968 JS
  1970 %Search_Machines = (
  1971         "google" =>     {   "query" =>  "http://www.google.com/search?q=" ,
  1972                     "icon"  =>  "$Config{frontend_google_ico}" },
  1973         "freebsd" =>    {   "query" =>  "http://www.freebsd.org/cgi/man.cgi?query=",
  1974                     "icon"  =>  "$Config{frontend_freebsd_ico}" },
  1975         "linux"  =>     {   "query" =>  "http://man.he.net/?topic=",
  1976                     "icon"  =>  "$Config{frontend_linux_ico}"},
  1977         "opennet"  =>   {   "query" =>  "http://www.opennet.ru/search.shtml?words=",
  1978                     "icon"  =>  "$Config{frontend_opennet_ico}"},
  1979         "local" =>  {   "query" =>  "http://www.freebsd.org/cgi/man.cgi?query=",
  1980                     "icon"  =>  "$Config{frontend_local_ico}" },
  1982     );
  1984 %Elements_Visibility = (
  1985         "0 new_commands_table"      =>  "новые команды",
  1986         "1 diff"      =>  "редактор",
  1987         "2 time"      =>  "время",
  1988         "3 ttychange"     =>  "терминал",
  1989         "4 wrong_output wrong_cline wrong_root_output wrong_root_cline" 
  1990                 =>  "команды с ненулевым кодом завершения",
  1991         "5 mistyped_output mistyped_cline mistyped_root_output mistyped_root_cline" 
  1992                 =>  "неверно набранные команды",
  1993         "6 interrupted_output interrupted_cline interrupted_root_output interrupted_root_cline" 
  1994                 =>  "прерванные команды",
  1995         "7 tab_completion_output tab_completion_cline"    
  1996                 =>  "продолжение с помощью tab"
  1997 );
  1999 @Day_Name      = qw/ Воскресенье Понедельник Вторник Среда Четверг Пятница Суббота /;
  2000 @Month_Name    = qw/ Январь Февраль Март Апрель Май Июнь Июль Август Сентябрь Октябрь Ноябрь Декабрь /;
  2001 @Of_Month_Name = qw/ Января Февраля Марта Апреля Мая Июня Июля Августа Сентября Октября Ноября Декабря /;
  2002 }
  2007 # Временно удалённый код
  2008 # Возможно, он не понадобится уже никогда
  2011 sub search_by
  2012 {
  2013     my $sm = shift;
  2014     my $topic = shift;
  2015     $topic =~ s/ /+/;
  2017     return "<a href='". $Search_Machines{$sm}->{"query"}."$topic'><img width='16' height='16' src='".
  2018                 $Search_Machines{$sm}->{"icon"}."' border='0'/></a>";
  2019 }
  2024 ########################################################################################
  2025 #
  2026 # mywi
  2027 #
  2028 # 
  2029 #
  2030 #
  2031 #
  2032 #
  2033 #
  2037 sub mywi_init
  2038 {
  2039     our $MyWiFile = "/home/igor/mywi/mywi.txt";
  2040     our $MyWiLog = "/home/igor/mywi/mywi.log";
  2041     our $section="";
  2043     our @MywiTXT;       # Массив текстовых записей mywi
  2044     our %MywiHASH;      # Хэш массивов записей
  2045     our %Query;
  2047     load_mywitxt($MyWiFile, \@MywiTXT, \%MywiHASH);
  2048 }
  2050 sub mywi_process_query($)
  2051 #
  2052 # Сделать подсказку по заданному запросу
  2053 # $_[0] - тема для подсказки
  2054 # 
  2055 # Возвращает:
  2056 #   строку-подсказку
  2057 #
  2058 {
  2059     my $query = shift;
  2060     parse_query($query, \%Query);
  2061     $result = search_in_txt(\%Query, \@MywiTXT, \%MywiHASH);
  2063     if (!$result) {
  2064         #add_to_log(\%Query, $MyWiLog);
  2065         return "$query nothing appropriate.  Logged. ".join (";",%Query);
  2066     }   
  2068     return $result;
  2069 }
  2071 ####################################################################################
  2072 #                                   private section
  2073 ####################################################################################
  2075 sub load_mywitxt
  2076 #
  2077 # Загрузить файл с записями Mywi_TXT
  2078 # в массив
  2079 # $_[0] - указатель на массив для загрузки
  2080 # $_[1] - имя файла для загрузки
  2081 # 
  2082 {
  2083     my $MyWiFile = $_[0];
  2084     my $MywiTXT = $_[1];
  2085     my $MywiHASH = $_[2];
  2087     open (MW, "$MyWiFile") or die "Can't open $MyWiFile for reading";
  2088     binmode MW, ":utf8";
  2089     @{$MywiTXT} = <MW>;
  2090     close (MWF);
  2092     for my $mywi_line (@{$MywiTXT}) {
  2093         my $topic = $mywi_line;
  2094         $topic =~ s@\s*\(.*\n@@;
  2095         push @{$$MywiHASH{"$topic"}}, $mywi_line;
  2096 #        $MywiHASH{"$topic"} .= $mywi_line;
  2097     }
  2098 }
  2100 sub parse_query
  2101 #
  2102 # Строка запроса:
  2103 #   [format:]topic[(section)]
  2104 # Элементы format и topic являются не обязательными
  2105 #
  2106 # $_[0] - строка запроса
  2107 # $_[1] - ссылка на хэш запроса
  2108 #
  2109 {
  2110     my $query_string = shift;
  2111     my $query_hash = shift;
  2113     %{$query_hash} = (
  2114         "format"    =>  "txt",
  2115         "section"   =>  "",
  2116         "topic" =>  "",
  2117     );
  2119     if ($query_string =~ s/^([^:]*)://) {
  2120         $query_hash->{"format"} = $1 || "txt";
  2121     }
  2122     if ($query_string =~ s/\(([^(]*)\)$//) {
  2123         $query_hash->{"section"} = $1 || "";
  2124     }
  2125     $query_hash->{"topic"} = $query_string;
  2126 }
  2129 sub search_in_txt
  2130 #
  2131 # Выполнить поиск в текстовой базе 
  2132 # по известному запросу
  2133 # $_[0] -- ссылка на хэш запроса
  2134 # $_[1] -- ссылка на массив текстовых записей
  2135 # $_[2] -- ссылка на хэш массивов текстовых записей
  2136 # Результат:
  2137 #   найденная текстовая запись в заданном формате
  2138 #
  2139 {
  2140     my %Query = %{$_[0]};
  2141     my %MywiHASH = %{$_[2]};
  2143     my $topic = $Query{"topic"};
  2144     my $section = $Query{"section"};
  2145     my $result = "";
  2147     return join("\n",@{$MywiHASH{"$topic"}})."\n";
  2149     for my $l (@{$$_[2]{$topic}}) {
  2150 #    for my $l (@{$_[1]}) {
  2151         my $line = $l;
  2152         if (
  2153             ($section and $line =~ /^\s*\Q$topic\E\s*\($section*\)\s*-/ )
  2154             or (not $section and $line =~ /^\s*\Q$topic\E\s*(\([^)]*\)?)\s*-/) ) {
  2155             $line =~ s/^.* -//mg if ($Config{"short"});
  2156             $result .= "<para>$line</para>";
  2157         }
  2158     }
  2159     return $result;
  2160 }
  2163 sub add_to_log($$)
  2164 #
  2165 # Если в базе отсутствует информация по данной теме, 
  2166 # сделать предположение доступным способом
  2167 # и добавить его в базу
  2168 # или просто сделать отметку о необходимости 
  2169 # расширения базы
  2170 #
  2171 # Добавить запись в журнал
  2172 # $_[0] - запись (ссылка на хэш)
  2173 # $_[1] - имя файла-журнала
  2174 #
  2175 {
  2176     my $query = $_[0];
  2177     my $MyWiLog = $_[1];
  2179     open (MWF, ">>:utf8", $MyWiLog) or die "Can't open $MyWiLog for writing";
  2180     my $my_guess = mywi_guess($query);
  2181     print MWF "$my_guess\n";
  2182     close(MWF);
  2183 }
  2185 sub mywi_guess($)
  2186 # Сформировать исходную строку для журнала по заданному запросу
  2187 # Если секция принадлежит 0..9, в качестве основы для результирующего текста использовать whatis
  2188 # $_[0] - запись (ссылка на хэш)
  2189 # 
  2190 # Возвращает:
  2191 #   строку-предположение
  2192 {
  2193     my %query = %{$_[0]};
  2195     my $topic = $query{"topic"};
  2196     my $section = $query{"section"};
  2198     my $result = "$topic($section)";
  2199     if (!$section or $section =~ /^[1-9]$/)
  2200     {
  2201         # Запрос из категории 1-9
  2202         # Об этом может знать whatis
  2203         $result = `LANG=C whatis -- "$topic"`;
  2204         if ($result =~ /nothing appropriate/i) {
  2205             $result = $topic;
  2206             $result .= "($section)" if $section;
  2207         }
  2208         else {
  2209             1 while ($result =~ s/(\s+)-(\s+)/$1+$2/sg);
  2210             $result =~ s/\s+\(/(/;
  2211             chomp $result;
  2212         }
  2213     }   
  2214     return $result;
  2215 }
