lilalo
view l3-frontend @ 111:99ea38e538c9
Добавил:
* l3upload
Исправил:
* хинт теперь всплывает только при наведении непосредственно на команду
(а не на приглашение и не на символ кода завершения)
* подсветка неизвестных команд не такая сильная
* l3upload
Исправил:
* хинт теперь всплывает только при наведении непосредственно на команду
(а не на приглашение и не на символ кода завершения)
* подсветка неизвестных команд не такая сильная
| author | igor | 
|---|---|
| date | Sat Feb 16 13:41:48 2008 +0200 (2008-02-16) | 
| parents | 3cd466f35ad6 | 
| children | 658b4ea105c1 | 
 line source
     1 #!/usr/bin/perl -w
     3 use POSIX qw(strftime);
     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 %Sessions;
    14 our $debug_output="";      # Используйте эту переменную, если нужно передать отладочную информацию
    16 our %filter;
    17 our $filter_url;
    18 sub init_filter;
    20 our %Files;
    22 # vvv Инициализация переменных выполняется процедурой init_variables
    23 our @Day_Name;
    24 our @Month_Name;
    25 our @Of_Month_Name;
    26 our %Search_Machines;
    27 our %Elements_Visibility;
    28 # ^^^
    30 our $First_Command=$0;
    31 our $Last_Command=40;
    33 our %Stat;
    34 our %frequency_of_command; # Сколько раз в журнале встречается какая команда
    35 our $table_number=1;
    36 our %tigra_hints;
    38 my %mywi_cache_for;         # Кэш для экономии обращений к mywi
    40 sub count_frequency_of_commands;
    41 sub make_comment;
    42 sub make_new_entries_table;
    43 sub load_command_lines_from_xml;
    44 sub load_sessions_from_xml;
    45 sub sort_command_lines;
    46 sub process_command_lines;
    47 sub init_variables;
    48 sub main;
    49 sub collapse_list($);
    51 sub minutes_passed;
    53 sub print_all_txt;
    54 sub print_all_html;
    55 sub print_edit_all_html;
    56 sub print_command_lines_html;
    57 sub print_command_lines_txt;
    58 sub print_files_html;
    59 sub print_stat_html;
    60 sub print_header_html;
    61 sub print_footer_html;
    62 sub tigra_hints_generate;
    64 #### mywi
    65 # 
    66 sub mywi_init;
    67 sub load_mywitxt;
    68 sub mywi_process_query($);
    69 #
    70 sub add_to_log($$);
    71 sub parse_query;
    72 sub search_in_txt;
    73 sub add_to_log($$);
    74 sub mywi_guess($);
    75 #
    77 main();
    79 sub main
    80 {
    81     $| = 1;
    83     init_variables();
    84     init_config();
    85     $Config{frontend_ico_path}=$Config{frontend_css};
    86     $Config{frontend_ico_path}=~s@/[^/]*$@@;
    87     init_filter();
    88     mywi_init();
    90     load_command_lines_from_xml($Config{"backend_datafile"});
    91     load_sessions_from_xml($Config{"backend_datafile"});
    92     sort_command_lines;
    93     process_command_lines;
    94     if (defined($filter{action}) && $filter{action} eq "edit") {
    95         print_edit_all_html($Config{"output"});
    96     }
    97     else {
    98         print_all_html($Config{"output"});
    99     }
   100 }
   102 sub init_filter
   103 {
   104     if ($Config{filter}) {
   105         # Инициализация фильтра
   106         for (split /&/,$Config{filter}) {
   107             my ($var, $val) = split /=/;
   108             $filter{$var} = $val || "";
   109         }
   110     }
   111     $filter_url = join ("&", map("$_=$filter{$_}", keys %filter));
   112 }
   114 # extract_from_cline
   116 # In:   $what       = commands | args
   117 # Out:  return      ссылка на хэш, содержащий результаты разбора
   118 #                   команда => позиция
   120 # Разобрать командную строку $_[1] и возвратить хэш, содержащий 
   121 # номер первого появление команды в строке:
   122 #   команда => первая позиция
   123 sub extract_from_cline
   124 {
   125     my $what = $_[0];
   126     my $cline = $_[1];
   127     my @lists = split /\;/, $cline;
   130     my @command_lines = ();
   131     for my $command_list (@lists) {
   132         push(@command_lines, split(/\|/, $command_list));
   133     }
   135     my %position_of_command;
   136     my %position_of_arg;
   137     my $i=0;
   138     for my $command_line (@command_lines) {
   139         $command_line =~ s@^\s*@@;
   140         $command_line =~ /\s*(\S+)\s*(.*)/;
   141         if ($1 && $1 eq "sudo" ) {
   142             $position_of_command{"$1"}=$i++;
   143             $command_line =~ s/\s*sudo\s+//;
   144         }
   145         if ($command_line !~ m@^\s*\S*/etc/@) {
   146             $command_line =~ s@^\s*\S+/@@;
   147         }
   149         $command_line =~ /\s*(\S+)\s*(.*)/;
   150         my $command = $1;
   151         my $args = $2;
   152         if ($command && !defined $position_of_command{"$command"}) {
   153                 $position_of_command{"$command"}=$i++;
   154         };  
   155         if ($args) {
   156             my @args = split (/\s+/, $args);
   157             for my $a (@args) {
   158                 $position_of_arg{"$a"}=$i++
   159                     if !defined $position_of_arg{"$a"};
   160             };  
   161         }
   162     }
   164     if ($what eq "commands") {
   165         return \%position_of_command;
   166     } else {
   167         return \%position_of_arg;
   168     }
   170 }
   172 sub mywrap($)
   173 {
   174 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].
   175 '</div></div></div></div></div></div></div></div>';
   176 }
   178 sub tigra_hints_generate
   179 {
   180     my $tigra_hints_items="";
   181     for my $hint_id (keys %tigra_hints) {
   182         $tigra_hints{$hint_id} =~ s@\n@<br/>@gs;
   183         $tigra_hints{$hint_id} =~ s@ - @ — @gs;
   184         $tigra_hints{$hint_id} =~ s@'@\\'@gs;
   185 #        $tigra_hints_items .= "'$hint_id' : mywrap('".$tigra_hints{$hint_id}."'),";
   186         $tigra_hints_items .= "'$hint_id' : '".mywrap($tigra_hints{$hint_id})."',";
   187     }
   188     $tigra_hints_items =~ s/,$//; 
   189     return <<TIGRA;
   191 var HINTS_CFG = {
   192 	'top'        : 5, // a vertical offset of a hint from mouse pointer
   193 	'left'       : 5, // a horizontal offset of a hint from mouse pointer
   194 	'css'        : 'hintsClass', // a style class name for all hints, TD object
   195 	'show_delay' : 500, // a delay between object mouseover and hint appearing
   196 	'hide_delay' : 2000, // a delay between hint appearing and hint hiding
   197 	'wise'       : true,
   198 	'follow'     : true,
   199 	'z-index'    : 0 // a z-index for all hint layers
   200 },
   202 HINTS_CFG_NEW = {
   203     'wise'       : true, // don't go off screen, don't overlap the object in the document
   204     'margin'     : 10, // minimum allowed distance between the hint and the window edge (negative values accepted)
   205     'gap'        : 20, // minimum allowed distance between the hint and the origin (negative values accepted)
   206     '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)
   207     'css'        : 'hintsClass', // a style class name for all hints, applied to DIV element (see style section in the header of the document)
   208     'show_delay' : 0, // a delay between initiating event (mouseover for example) and hint appearing
   209     'hide_delay' : 200, // a delay between closing event (mouseout for example) and hint disappearing
   210     'follow'     : true, // hint follows the mouse as it moves
   211     'z-index'    : 100, // a z-index for all hint layers
   212     'IEfix'      : false, // fix IE problem with windowed controls visible through hints (activate if select boxes are visible through the hints)
   213     'IEtrans'    : ['blendTrans(DURATION=.3)', null], // [show transition, hide transition] - nice transition effects, only work in IE5+
   214     'opacity'    : 90 // opacity of the hint in %%
   215 },
   217 HINTS_ITEMS = {
   218     $tigra_hints_items
   219 };
   220 var myHint = new THints (HINTS_CFG, HINTS_ITEMS);
   223 function mywrap (s_) {
   224 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_+
   225 '</div></div></div></div></div></div></div></div>';
   227 }
   228 TIGRA
   229 $a=<<TIGRA;
   230 TIGRA
   231 }
   234 sub count_frequency_of_commands
   235 {
   236     my $cline = $_[0];
   237     my @commands = keys %{extract_from_cline("commands", $cline)};
   238     for my $command (@commands) {
   239         $frequency_of_command{$command}++;
   240     }
   241 }
   243 sub make_comment
   244 {
   245     my $cline = $_[0];
   246     #my $files = $_[1];
   248     my @comments;
   249     my @commands = keys %{extract_from_cline("commands", $cline)};
   250     my @args = keys %{extract_from_cline("args", $cline)};
   251     return if (!@commands && !@args);
   252     #return "commands=".join(" ",@commands)."; files=".join(" ",@files);
   254     # Commands
   255     for my $command (@commands) {
   256         $command =~ s/'//g;
   257         #$frequency_of_command{$command}++;
   258         if (!$Commands_Description{$command}) {
   259             $mywi_cache_for{$command} ||= mywi_process_query($command) || "";
   260             my $mywi = join ("\n", grep(/\([18]|sh|script\)/, split(/\n/, $mywi_cache_for{$command})));
   261             $mywi =~ s/\s+/ /;
   262             if ($mywi !~ /^\s*$/) {
   263                 $Commands_Description{$command} = $mywi;
   264             }
   265             else {
   266                 next;
   267             }
   268         }
   270         push @comments, $Commands_Description{$command};
   271     }
   272     return join("
\n", @comments);
   274     # Files
   275     for my $arg (@args) {
   276         $arg =~ s/'//g;
   277         if (!$Args_Description{$arg}) {
   278             my $mywi;
   279             $mywi = mywi_client ($arg);
   280             $mywi = join ("\n", grep(/\([5]\)/, split(/\n/, $mywi)));
   281             $mywi =~ s/\s+/ /;
   282             if ($mywi !~ /^\s*$/) {
   283                 $Args_Description{$arg} = $mywi;
   284             }
   285             else {
   286                 next;
   287             }
   288         }
   290         push @comments, $Args_Description{$arg};
   291     }
   293 }
   295 =cut
   296 Процедура load_command_lines_from_xml выполняет загрузку разобранного lab-скрипта
   297 из XML-документа в переменную @Command_Lines
   299 # In:       $datafile           имя файла
   300 # Out:      @CommandLines       загруженные командные строки
   302 Предупреждение!
   303 Процедура не в состоянии обрабатывать XML-документ любой структуры.
   304 В действительности файл cache из которого загружаются данные 
   305 просто напоминает XML с виду.
   306 =cut
   307 sub load_command_lines_from_xml
   308 {
   309     my $datafile = $_[0];
   311     open (CLASS, $datafile)
   312         or die "Can't open file with xml lablog ",$datafile,"\n";
   313     local $/;
   314     binmode CLASS, ":utf8";
   315     $data = <CLASS>;
   316     close(CLASS);
   318     for $command ($data =~ m@<command>(.*?)</command>@sg) {
   319         my %cl;
   320         while ($command =~ m@<([^>]*?)>(.*?)</\1>@sg) {
   321             $cl{$1} = $2;
   322         }
   323         push @Command_Lines, \%cl;
   324     }
   325 }
   327 sub load_sessions_from_xml
   328 {
   329     my $datafile = $_[0];
   331     open (CLASS,  $datafile)
   332         or die "Can't open file with xml lablog ",$datafile,"\n";
   333     local $/;
   334     binmode CLASS, ":utf8";
   335     my $data = <CLASS>;
   336     close(CLASS);
   338     my $i=0;
   339     for my $session ($data =~ m@<session>(.*?)</session>@msg) {
   340         my %session_hash;
   341         while ($session =~ m@<([^>]*?)>(.*?)</\1>@sg) {
   342             $session_hash{$1} = $2;
   343         }
   344         $Sessions{$session_hash{local_session_id}} = \%session_hash;
   345     }
   346 }
   349 # sort_command_lines
   350 # In:   @Command_Lines
   351 # Out:  @Command_Lies_Index
   353 sub sort_command_lines
   354 {
   356     my @index;
   357     for (my $i=0;$i<=$#Command_Lines;$i++) {
   358         $index[$i]=$i;
   359     }
   361     @Command_Lines_Index = sort {
   362         $Command_Lines[$index[$a]]->{"time"} <=> $Command_Lines[$index[$b]]->{"time"}
   363     } @index;
   365 }
   367 ##################
   368 # process_command_lines
   369 #
   370 # Обрабатываются командные строки @Command_Lines
   371 # Для каждой строки определяется:
   372 #   class   класс    
   373 #   note    комментарий 
   374 #
   375 # In:        @Command_Lines_Index
   376 # In-Out:    @Command_Lines
   378 sub process_command_lines
   379 {
   382     my $current_command=0;
   384 COMMAND_LINE_PROCESSING:
   385     for my $i (@Command_Lines_Index) {
   387         $current_command++;
   388         next if $current_command < $Config{"start_from_command"};
   389         last if $current_command > $Config{"start_from_command"} + $Config{"commands_to_show_at_a_go"};
   391         my $cl = \$Command_Lines[$i];
   393         next if !$cl;
   395         for my $filter_key (keys %filter) {
   396             next COMMAND_LINE_PROCESSING
   397                 if defined($$cl->{local_session_id})
   398                 && defined($Sessions{$$cl->{local_session_id}}->{$filter_key})
   399                 && $Sessions{$$cl->{local_session_id}}->{$filter_key} ne $filter{$filter_key};
   400         }
   402         $$cl->{id} = $$cl->{"time"};
   404         $$cl->{err} ||=0;
   406         # Класс команды
   408         $$cl->{"class"} =   $$cl->{"err"} eq 130 ?  "interrupted"
   409                         :   $$cl->{"err"} eq 127 ?  "mistyped"
   410                         :   $$cl->{"err"}        ?  "wrong"
   411                         :                           "normal";
   413         if ($$cl->{"cline"} && 
   414             $$cl->{"cline"} =~ /[^|`]\s*sudo/
   415             || $$cl->{"uid"} eq 0) {
   416             $$cl->{"class"}.="_root";
   417         }
   419         my $hint;
   420         count_frequency_of_commands($$cl->{"cline"});
   421         $hint = make_comment($$cl->{"cline"});
   423         if ($hint) {
   424             $$cl->{hint} = $hint;
   425         }
   426         $tigra_hints{$$cl->{"time"}} = $hint;
   428         #$$cl->{hint}="";
   430 # Выводим <head_lines> верхних строк
   431 # и <tail_lines> нижних строк,
   432 # если эти параметры существуют
   433         my $output="";
   435         if ($$cl->{"last_command"} eq "cat" && !$$cl->{"err"} && !($$cl->{"cline"} =~ /</)) {
   436             my $filename = $$cl->{"cline"};
   437             $filename =~ s/.*\s+(\S+)\s*$/$1/;
   438             $Files{$filename}->{"content"} = $$cl->{"output"};
   439            $Files{$filename}->{"source_command_id"} = $$cl->{"id"}
   440         }
   441         my @lines = split '\n', $$cl->{"output"};
   442         if ((
   443              $Config{"head_lines"} 
   444              || $Config{"tail_lines"}
   445              )
   446              && $#lines >  $Config{"head_lines"} + $Config{"tail_lines"} ) {
   447 #
   448             for (my $i=0; $i<= $#lines && $i < $Config{"head_lines"}; $i++) {
   449                 $output .= $lines[$i]."\n";
   450             }
   451             $output .= $Config{"skip_text"}."\n";
   453             my $start_line=$#lines-$Config{"tail_lines"}+1;
   454             for (my $i=$start_line; $i<= $#lines; $i++) {
   455                 $output .= $lines[$i]."\n";
   456             }
   457         } 
   458         else {
   459            $output = $$cl->{"output"};
   460         }
   461         $$cl->{short_output} = $output;
   463 #Обработка пометок
   464 #  Если несколько пометок (notes) идут подряд, 
   465 #  они все объединяются
   467         if ($$cl->{cline} =~ /l3shot/) {
   468                 if ($$cl->{output} =~ m@Screenshot is written to.*/(.*)\.xwd@) {
   469                     $$cl->{screenshot}="$1".$Config{l3shot_suffix};
   470                 }
   471         }
   472         if ($$cl->{cline} =~ /l3upload/) {
   473                 if ($$cl->{output} =~ m@Uploaded file name is (.*)@) {
   474                     $$cl->{screenshot}="$1";
   475                 }
   476         }
   478         if ($$cl->{cline}=~ m@cat[^#]*#([\^=v])\s*(.*)@) {
   480             my $note_operator = $1;
   481             my $note_title = $2;
   483             if ($note_operator eq "=") {
   484                 $$cl->{"class"} = "note";
   485                 $$cl->{"note"} = $$cl->{"output"};
   486                 $$cl->{"note_title"} = $2;
   487             }
   488             else {
   489                 my $j = $i;
   490                 if ($note_operator eq "^") {
   491                     $j--;
   492                     $j-- while ($j >=0  && (!$Command_Lines[$j] || $Command_Lines[$j]->{tty} ne $$cl->{tty}));
   493                 }
   494                 elsif ($note_operator eq "v") {
   495                     $j++;
   496                     $j++ while ($j <= @Command_Lines  && (!$Command_Lines[$j] || $Command_Lines[$j]->{tty} ne $$cl->{tty}));
   497                 }
   498                 $Command_Lines[$j]->{note_title}=$note_title;
   499                 $Command_Lines[$j]->{note}.=$$cl->{output};
   500                 $$cl=0;
   501             }
   502         }
   503         elsif ($$cl->{cline}=~ /#([\^=v])(.*)/) {
   505             my $note_operator = $1;
   506             my $note_text = $2;
   508             if ($note_operator eq "=") {
   509                 $$cl->{"class"} = "note";
   510                 $$cl->{"note"} = $note_text;
   511             }
   512             else {
   513                 my $j=$i;
   514                 if ($note_operator eq "^") {
   515                     $j--;
   516                     $j-- while ($j >=0  && (!$Command_Lines[$j] || $Command_Lines[$j]->{tty} ne $$cl->{tty}));
   517                 }
   518                 elsif ($note_operator eq "v") {
   519                     $j++;
   520                     $j++ while ($j <= @Command_Lines  && $Command_Lines[$j]->{tty} ne $$cl->{tty} || !$Command_Lines[$j]);
   521                 }
   522                 $Command_Lines[$j]->{note}.="$note_text\n";
   523                 $$cl=0;
   524             }
   525         }
   526         if ($$cl->{"class"} eq "note") {
   527                 my $note_html = $$cl->{note};
   528                 $note_html = join ("\n", map ("<p>$_</p>", split (/-\n/, $note_html)));
   529                 $note_html =~ s@(http:[a-zA-Z.0-9/?\_%-]*)@<a href='$1'>$1</a>@g;
   530                 $note_html =~ s@(www\.[a-zA-Z.0-9/?\_%-]*)@<a href='$1'>$1</a>@g;
   531                 $$cl->{"note_html"} = $note_html;
   532         }
   533     }   
   535 }
   538 =cut
   539 Процедура print_command_lines выводит HTML-представление
   540 разобранного lab-скрипта. 
   542 Разобранный lab-скрипт должен находиться в массиве @Command_Lines
   543 =cut
   545 sub print_command_lines_html
   546 {
   548     my @toc;                # Оглавление
   549     my $note_number=0;
   551     my $result = q();
   552     my $this_day_resut = q();
   554     my $cl;
   555     my $last_tty="";
   556     my $last_session="";
   557     my $last_day=q();
   558     my $last_wday=q();
   559     my $first_command_of_the_day_unix_time=q();
   560     my $human_readable_time=q();
   561     my $in_range=0;
   563     my $current_command=0;
   565     my @known_commands;
   569     $Stat{LastCommand}   ||= 0;
   570     $Stat{TotalCommands} ||= 0;
   571     $Stat{ErrorCommands} ||= 0;
   572     $Stat{MistypedCommands} ||= 0;
   574     my %new_entries_of = (
   575         "1 1"     =>   "программы пользователя",
   576         "2 8"     =>   "программы администратора",
   577         "3 sh"    =>   "команды интерпретатора",
   578         "4 script"=>   "скрипты",
   579     );
   581 COMMAND_LINE:
   582     for my $k (@Command_Lines_Index) {
   584         my $cl=$Command_Lines[$Command_Lines_Index[$current_command++]];
   585         next unless $cl;
   587         next if $current_command < $Config{"start_from_command"};
   588         last if $current_command > $Config{"start_from_command"} + $Config{"commands_to_show_at_a_go"};
   591 # Пропускаем команды, с одинаковым временем
   592 # Это не совсем правильно.
   593 # Возможно, что это команды, набираемые с помощью <completion>
   594 # или запомненные с помощью <ctrl-c>
   596         next if $Stat{LastCommand} == $cl->{time};
   598 # Пропускаем строки, которые противоречат фильтру
   599 # Если у нас недостаточно информации о том, подходит строка под  фильтр или нет, 
   600 # мы её выводим
   602         for my $filter_key (keys %filter) {
   603             next COMMAND_LINE 
   604                 if defined($cl->{local_session_id})
   605                 && defined($Sessions{$cl->{local_session_id}}->{$filter_key})
   606                 && $Sessions{$cl->{local_session_id}}->{$filter_key} ne $filter{$filter_key};
   607         }
   609 # Набираем статистику
   610 # Хэш %Stat
   612         $Stat{FirstCommand} = $cl->{time} unless $Stat{FirstCommand};
   613         if ($cl->{time} - $Stat{LastCommand} < $Config{stat_inactivity_interval}) {
   614             $Stat{TotalTime} += $cl->{time} - $Stat{LastCommand}
   615         }
   616         my $seconds_since_last_command = $cl->{time} - $Stat{LastCommand};
   618         if ($Stat{LastCommand} > $cl->{time}) {
   619                $result .= "Время идёт вспять<br/>";
   620         };
   621         $Stat{LastCommand} = $cl->{time};
   622         $Stat{TotalCommands}++;
   624 # Пропускаем строки, выходящие за границу "signature",
   625 # при условии, что границы указаны
   626 # Пропускаем неправильные/прерванные/другие команды
   627         if ($Config{"from"} && $cl->{"cline"} =~ /$Config{"signature"}\s*$Config{"from"}/) {
   628             $in_range=1;
   629             next;
   630         }
   631         if ($Config{"to"} && $cl->{"cline"} =~ /$Config{"signature"}\s*$Config{"to"}/) {
   632             $in_range=0;
   633             next;
   634         }
   635         next    if ($Config{"from"} && $Config{"to"}   && !$in_range) 
   636                 || ($Config{"skip_empty"} =~ /^y/i     && $cl->{"cline"} =~ /^\s*$/ )
   637                 || ($Config{"skip_wrong"} =~ /^y/i     && $cl->{"err"} != 0)
   638                 || ($Config{"skip_interrupted"} =~ /^y/i && $cl->{"err"} == 130);
   643 #
   644 ##
   645 ## Начинается собственно вывод
   646 ##
   647 #
   649 ### Сначала обрабатываем границы разделов
   650 ### Если тип команды "note", это граница
   652         if ($cl->{class} eq "note") {
   653             $this_day_result .= "<tr><td colspan='6'>"
   654                              .  "<h4 id='note$note_number'>".$cl->{note_title}."</h4>" if $cl->{note_title}
   655                              .  "".$cl->{note_html}."<p/><p/></td></tr>";
   657             if ($cl->{note_title}) {
   658                 push @{$toc[@toc]},"<a href='#note$note_number'>".$cl->{note_title}."</a>";
   659                 $note_number++;
   660             }
   661             next;
   662         }
   664         my ($sec,$min,$hour,$day,$mon,$year,$wday,$yday,$isdst) = localtime($cl->{time});
   667         # Добавляем спереди 0 для удобочитаемости
   668         $min  = "0".$min  if $min  =~ /^.$/;
   669         $hour = "0".$hour if $hour =~ /^.$/;
   670         $sec  = "0".$sec  if $sec  =~ /^.$/;
   672         $class=$cl->{"class"};
   673         $Stat{ErrorCommands}++          if $class =~ /wrong/;
   674         $Stat{MistypedCommands}++       if $class =~ /mistype/;
   676 # DAY CHANGE
   677         if ( $last_day ne $day) {
   678             $prev_unix_time=$first_command_of_the_day_unix_time;
   679             $first_command_of_the_day_unix_time = $cl->{time};
   680             $human_readable_time = strftime "%D", localtime($prev_unix_time);
   681             if ($last_day) {
   683 # Вычисляем разность множеств.
   684 # Что-то вроде этого, если бы так можно было писать:
   685 #   @new_commands = keys %frequency_of_command - @known_commands;
   688 # Выводим предыдущий день
   690                 $result .= "<h3 id='day_on_sec_$prev_unix_time'>".$Day_Name[$last_wday]." ($human_readable_time)</h3>";
   691                 for my $entry_class (sort keys %new_entries_of) {
   692                     my $table_caption = "Таблица ".$table_number++.".".$Day_Name[$last_wday]
   693                                         .". Новые ".$new_entries_of{$entry_class};
   694                     my $new_commands_section = make_new_entries_table(
   695                                                 $table_caption, 
   696                                                 $entry_class=~/[0-9]+\s+(.*)/, 
   697                                                 \@known_commands);
   698                 }
   699                 @known_commands = keys %frequency_of_command;
   700                 $result .= $this_day_result;
   701             }
   703 # Добавляем текущий день в оглавление
   705             $human_readable_time = strftime "%D", localtime($first_command_of_the_day_unix_time);
   706             push @toc, "<a href='#day_on_sec_$first_command_of_the_day_unix_time'>".$Day_Name[$wday]." ($human_readable_time)</a>\n";
   709             $last_day=$day;
   710             $last_wday=$wday;
   711             $this_day_result = q();
   712         }
   713         else {
   714             $this_day_result .= minutes_passed($seconds_since_last_command);
   715         }
   717         $this_day_result .= "<div class='command' id='command:".$cl->{"id"}."' >\n";
   719 # CONSOLE CHANGE
   720         if ($cl->{"tty"} && $last_tty ne $cl->{"tty"} && 0) {
   721             my $tty = $cl->{"tty"};
   722             $this_day_result .= "<div class='ttychange'>"
   723                                 . $tty
   724                                 ."</div>";
   725             $last_tty=$cl->{"tty"};
   726         }
   728 # Session change
   729         if ( $last_session ne $cl->{"local_session_id"}) {
   730             my $tty;
   731             if (defined $Sessions{$cl->{"local_session_id"}}->{"tty"}) {
   732                 $this_day_result .= "<div class='ttychange'><a href='?local_session_id=".$cl->{"local_session_id"}."'>"
   733                                 . $Sessions{$cl->{"local_session_id"}}->{"tty"}
   734                                 ."</a></div>";
   735             }
   736             $last_session=$cl->{"local_session_id"};
   737         }
   739 # TIME
   740         if ($Config{"show_time"} =~ /^y/i) {
   741             $this_day_result .= "<div class='time'>$hour:$min:$sec</div>" 
   742         }
   744 # COMMAND
   745         my $cline;
   746         $prompt_hint = join ("
", map("$_=$cl->{$_}", grep (!/^(output|diff)$/, sort(keys(%{$cl})))));
   747         $cline = "<span title='$prompt_hint'>".$cl->{"prompt"}."</span>"
   748                 ."<span onmouseover=\"myHint.show('".$cl->{time}."')\" onmouseout=\"myHint.hide()\">".$cl->{"cline"}."</span>";
   749         $cline =~ s/\n//;
   751         if ($cl->{"hint"}) {
   752 #            $cline = "<span title='$cl->{hint}' class='with_hint'>$cline</span>" ;
   753             $cline = "<span class='with_hint'>$cline</span>" ;
   754         } 
   755         else {
   756             $cline = "<span class='without_hint'>$cline</span>";
   757         }
   759         $this_day_result .= "<DIV class='fixed_div'><table cellpadding='0' cellspacing='0'><tr><td>\n<div class='cblock_$cl->{class}'>\n";
   760         $this_day_result .= "<div class='cline'>" . $cline ;      #cline
   761         $this_day_result .= "<span title='Код завершения ".$cl->{"err"}."'>\n"
   762                          .  "<img src='".$Config{frontend_ico_path}."/error.png'/>\n"
   763                          .  "</span>\n" if $cl->{"err"};
   764         $this_day_result .= "</div>\n";                             #cline
   766 # OUTPUT
   767         my $last_command = $cl->{"last_command"};
   768         if (!( 
   769         $Config{"suppress_editors"} =~ /^y/i && grep ($_ eq $last_command, @{$Config{"editors"}}) ||
   770         $Config{"suppress_pagers"}  =~ /^y/i && grep ($_ eq $last_command, @{$Config{"pagers"}}) ||
   771         $Config{"suppress_terminal"}=~ /^y/i && grep ($_ eq $last_command, @{$Config{"terminal"}})
   772             )) {
   773             $this_day_result .= "<pre class='output'>\n" . $cl->{short_output} . "</pre>\n";
   774         }
   776 # DIFF
   777         $this_day_result .= "<pre class='diff'>".$cl->{"diff"}."</pre>"
   778             if ( $Config{"show_diffs"} =~ /^y/i && $cl->{"diff"});
   779 # SHOT
   780         $this_day_result .= "<img src='"
   781                 .$Config{l3shot_path}
   782                 .$cl->{"screenshot"}
   783                 ."' alt ='screenshot id ".$cl->{"screenshot"}
   784                 ."'/>"
   785             if ( $Config{"show_screenshots"} =~ /^y/i && $cl->{"screenshot"});
   787 #NOTES
   788         if ( $Config{"show_notes"} =~ /^y/i && $cl->{"note"}) {
   789             my $note=$cl->{"note"};
   790             $note =~ s/\n/<br\/>\n/msg;
   791             if (not $note =~ s@(http:[a-zA-Z.0-9/_?%-]*)@<a href='$1'>$1</a>@g) {
   792               $note =~ s@(www\.[a-zA-Z.0-9/_?%-]*)@<a href='$1'>$1</a>@g;
   793             };
   794             $this_day_result .= "<div class='note'>";
   795             $this_day_result .= "<div class='note_title'>".$cl->{note_title}."</div>" if $cl->{note_title};
   796             $this_day_result .= "<div class='note_text'>".$note."</div>";
   797             $this_day_result .= "</div>\n";
   798         }
   800         # Вывод очередной команды окончен
   801         $this_day_result .= "</div>\n";                     # cblock
   802         $this_day_result .= "</td></tr></table></DIV>\n"
   803                          .  "</div>\n";                     # command
   804     }
   805     last: {
   806         $prev_unix_time=$first_command_of_the_day_unix_time;
   807         $first_command_of_the_day_unix_time = $cl->{time};
   808         $human_readable_time = strftime "%D", localtime($prev_unix_time);
   810         $result .= "<h3 id='day_on_sec_$prev_unix_time'>".$Day_Name[$last_wday]." ($human_readable_time)</h3>";
   812         for my $entry_class (keys %new_entries_of) {
   813             my $table_caption = "Таблица ".$table_number++.".".$Day_Name[$last_wday]
   814                               . ". Новые ".$new_entries_of{$entry_class};
   815             my $new_commands_section = make_new_entries_table(
   816                                         $table_caption, 
   817                                         $entry_class=~/[0-9]+\s+(.*)/, 
   818                                         \@known_commands);
   819         }
   820         @known_commands = keys %frequency_of_command;
   821         $result .= $this_day_result;
   822    }
   824     return ($result, collapse_list (\@toc));
   826 }
   828 #############
   829 # make_new_entries_table
   830 #
   831 # Напечатать таблицу неизвестных команд
   832 #
   833 # In:       $_[0]       table_caption
   834 #           $_[1]       entries_class
   835 #           @_[2..]     known_commands
   836 # Out:
   838 sub make_new_entries_table
   839 {
   840     my $table_caption;
   841     my $entries_class = shift;
   842     my @known_commands = @{$_[0]};
   843     my $result = "";
   845     my %count;
   846     my @new_commands = ();
   847     for my $c (keys %frequency_of_command, @known_commands) {
   848         $count{$c}++
   849     }
   850     for my $c (keys %frequency_of_command) {
   851         push @new_commands, $c if $count{$c} != 2;
   852     }
   854     my $new_commands_section;
   855     if (@new_commands){
   856         my $hint;
   857         for my $c (reverse sort { $frequency_of_command{$a} <=> $frequency_of_command{$b} } @new_commands) {
   858                 $hint = make_comment($c);
   859                 next unless $hint;
   860                 my ($command, $hint) = $hint =~ m/(.*?) \s*- \s*(.*)/;
   861                 next unless $command =~ s/\($entries_class\)//i;
   862                 $new_commands_section .= "<tr><td valign='top'>$command</td><td>$hint</td></tr>";
   863         }
   864     }
   865     if ($new_commands_section) {
   866         $result .= "<table class='new_commands_table' width='700' cellspacing='0' cellpadding='0'>"
   867                 .  "<tr class='new_commands_caption'>"
   868                 .  "<td colspan='2' align='right'>$table_caption</td>"
   869                 .  "</tr>"
   870                 .  "<tr class='new_commands_header'>"
   871                 .  "<td width=100>Команда</td><td width=600>Описание</td>"
   872                 .  "</tr>"
   873                 .  $new_commands_section 
   874                 .  "</table>"
   875     }
   876     return $result;
   877 }
   879 #############
   880 # minutes_passed
   881 #
   882 #
   883 #
   884 # In:       $_[0]       seconds_since_last_command
   885 # Out:                  "minutes passed" text
   887 sub minutes_passed
   888 {
   889         my $seconds_since_last_command = shift;
   890         my $result = "";
   891         if ($seconds_since_last_command > 7200) {
   892             my $hours_passed =  int($seconds_since_last_command/3600);
   893             my $passed_word  = $hours_passed % 10 == 1 ? "прошла"
   894                                                          : "прошло";
   895             my $hours_word   = $hours_passed % 10 == 1 ?   "часа":
   896                                                            "часов";
   897             $result .= "<div class='much_time_passed'>"
   898                     .  $passed_word." >".$hours_passed." ".$hours_word
   899                     .  "</div>\n";
   900         }
   901         elsif ($seconds_since_last_command > 600) {
   902             my $minutes_passed =  int($seconds_since_last_command/60);
   905             my $passed_word  = $minutes_passed % 100 > 10 
   906                             && $minutes_passed % 100 < 20 ? "прошло"
   907                              : $minutes_passed % 10 == 1  ? "прошла"
   908                                                           : "прошло";
   910             my $minutes_word = $minutes_passed % 100 > 10 
   911                             && $minutes_passed % 100 < 20 ? "минут" :
   912                                $minutes_passed % 10 == 1 ? "минута":
   913                                $minutes_passed % 10 == 0 ? "минут" :
   914                                $minutes_passed % 10  > 4 ? "минут" :
   915                                                            "минуты";
   917             if ($seconds_since_last_command < 1800) {
   918                 $result .= "<div class='time_passed'>"
   919                         .  $passed_word." ".$minutes_passed." ".$minutes_word
   920                         .  "</div>\n";
   921             }
   922             else {
   923                 $result .= "<div class='much_time_passed'>"
   924                         .  $passed_word." ".$minutes_passed." ".$minutes_word
   925                         .  "</div>\n";
   926             }
   927         }
   928         return $result;
   929 }
   931 #############
   932 # print_all_txt
   933 #
   934 # Вывести журнал в текстовом формате
   935 #
   936 # In:       $_[0]       output_filename
   937 # Out:
   939 sub print_command_lines_txt
   940 {
   942     my $output_filename=$_[0];
   943     my $note_number=0;
   945     my $result = q();
   946     my $this_day_resut = q();
   948     my $cl;
   949     my $last_tty="";
   950     my $last_session="";
   951     my $last_day=q();
   952     my $last_wday=q();
   953     my $in_range=0;
   955     my $current_command=0;
   957     my $cursor_position = 0;
   960     if ($Config{filter}) {
   961         # Инициализация фильтра
   962         for (split /&/,$Config{filter}) {
   963             my ($var, $val) = split /=/;
   964             $filter{$var} = $val || "";
   965         }
   966     }
   969 COMMAND_LINE:
   970     for my $k (@Command_Lines_Index) {
   972         my $cl=$Command_Lines[$Command_Lines_Index[$current_command++]];
   973         next unless $cl;
   976 # Пропускаем строки, которые противоречат фильтру
   977 # Если у нас недостаточно информации о том, подходит строка под  фильтр или нет, 
   978 # мы её выводим
   980         for my $filter_key (keys %filter) {
   981             next COMMAND_LINE 
   982                 if defined($cl->{local_session_id})
   983                 && defined($Sessions{$cl->{local_session_id}}->{$filter_key})
   984                 && $Sessions{$cl->{local_session_id}}->{$filter_key} ne $filter{$filter_key};
   985         }
   987 # Пропускаем строки, выходящие за границу "signature",
   988 # при условии, что границы указаны
   989 # Пропускаем неправильные/прерванные/другие команды
   990         if ($Config{"from"} && $cl->{"cline"} =~ /$Config{"signature"}\s*$Config{"from"}/) {
   991             $in_range=1;
   992             next;
   993         }
   994         if ($Config{"to"} && $cl->{"cline"} =~ /$Config{"signature"}\s*$Config{"to"}/) {
   995             $in_range=0;
   996             next;
   997         }
   998         next    if ($Config{"from"} && $Config{"to"}   && !$in_range) 
   999                 || ($Config{"skip_empty"} =~ /^y/i     && $cl->{"cline"} =~ /^\s*$/ )
  1000                 || ($Config{"skip_wrong"} =~ /^y/i     && $cl->{"err"} != 0)
  1001                 || ($Config{"skip_interrupted"} =~ /^y/i && $cl->{"err"} == 130);
  1004 #
  1005 ##
  1006 ## Начинается собственно вывод
  1007 ##
  1008 #
  1010 ### Сначала обрабатываем границы разделов
  1011 ### Если тип команды "note", это граница
  1013         if ($cl->{class} eq "note") {
  1014             $this_day_result .= " === ".$cl->{note_title}." === \n" if $cl->{note_title};
  1015             $this_day_result .= $cl->{note}."\n";
  1016             next;
  1017         }
  1019         my ($sec,$min,$hour,$day,$mon,$year,$wday,$yday,$isdst) = localtime($cl->{time});
  1021         # Добавляем спереди 0 для удобочитаемости
  1022         $min  = "0".$min  if $min  =~ /^.$/;
  1023         $hour = "0".$hour if $hour =~ /^.$/;
  1024         $sec  = "0".$sec  if $sec  =~ /^.$/;
  1026         $class=$cl->{"class"};
  1028 # DAY CHANGE
  1029         if ( $last_day ne $day) {
  1030             if ($last_day) {
  1031                 $result .= "== ".$Day_Name[$last_wday]." == \n";
  1032                 $result .= $this_day_result;
  1033             }
  1034             $last_day   = $day;
  1035             $last_wday  = $wday;
  1036             $this_day_result = q();
  1037         }
  1039 # CONSOLE CHANGE
  1040         if ($cl->{"tty"} && $last_tty ne $cl->{"tty"} && 0) {
  1041             my $tty = $cl->{"tty"};
  1042             $this_day_result .= "         #l3: ------- другая консоль ----\n";
  1043             $last_tty=$cl->{"tty"};
  1044         }
  1046 # Session change
  1047         if ( $last_session ne $cl->{"local_session_id"}) {
  1048             $this_day_result .= "# ------------------------------------------------------------"
  1049                              .  "  l3: local_session_id=".$cl->{"local_session_id"}
  1050                              .  " ---------------------------------- \n";
  1051             $last_session=$cl->{"local_session_id"};
  1052         }
  1054 # TIME
  1055         my @nl_counter = split (/\n/, $result);
  1056         $cursor_position=length($result) - @nl_counter;
  1058         if ($Config{"show_time"} =~ /^y/i) {
  1059             $this_day_result .= "$hour:$min:$sec" 
  1060         }
  1062 # COMMAND
  1063         $this_day_result .= " ".$cl->{"prompt"}.$cl->{"cline"}."\n";
  1064         if ($cl->{"err"}) {
  1065             $this_day_result .= "         #l3: err=".$cl->{'err'}."\n";
  1066         }
  1068 # OUTPUT
  1069         my $last_command = $cl->{"last_command"};
  1070         if (!( 
  1071         $Config{"suppress_editors"} =~ /^y/i && grep ($_ eq $last_command, @{$Config{"editors"}}) ||
  1072         $Config{"suppress_pagers"}  =~ /^y/i && grep ($_ eq $last_command, @{$Config{"pagers"}}) ||
  1073         $Config{"suppress_terminal"}=~ /^y/i && grep ($_ eq $last_command, @{$Config{"terminal"}})
  1074             )) {
  1075             my $output = $cl->{short_output};
  1076             if ($output) {
  1077                  $output =~ s/^/         |/mg;
  1078             }
  1079             $this_day_result .= $output;
  1080         }
  1082 # DIFF
  1083         if ( $Config{"show_diffs"} =~ /^y/i && $cl->{"diff"}) {
  1084             my $diff = $cl->{"diff"};
  1085             $diff =~ s/^/         |/mg;
  1086             $this_day_result .= $diff;
  1087         };
  1088 # SHOT
  1089         if ($Config{"show_screenshots"} =~ /^y/i && $cl->{"screenshot"}) {
  1090             $this_day_result .= "         #l3: screenshot=".$cl->{'screenshot'}."\n";
  1091         }
  1093 #NOTES
  1094         if ( $Config{"show_notes"} =~ /^y/i && $cl->{"note"}) {
  1095             my $note=$cl->{"note"};
  1096             $note =~ s/\n/\n#^/msg;
  1097             $this_day_result .= "#^ == ".$cl->{note_title}." ==\n" if $cl->{note_title};
  1098             $this_day_result .= "#^ ".$note."\n";
  1099         }
  1101     }
  1102     last: {
  1103         $result .= "== ".$Day_Name[$last_wday]." == \n";
  1104         $result .= $this_day_result;
  1105    }
  1107    return $result;
  1111 }
  1113 #############
  1114 # print_edit_all_html
  1115 #
  1116 # Вывести страницу с текстовым представлением журнала для редактирования
  1117 #
  1118 # In:       $_[0]       output_filename
  1119 # Out:
  1121 sub print_edit_all_html
  1122 {
  1123     my $output_filename= shift;
  1124     my $result;
  1125     my $cursor_position = 0;
  1127     $result = print_command_lines_txt;
  1128     my $title = ">Журнал лабораторных работ. Правка";
  1130     $result = 
  1131                "<html>"
  1132                 ."<head>"
  1133                 ."<meta content='text/html; charset=utf-8' http-equiv='Content-Type' />"
  1134                 ."<link rel='stylesheet' href='$Config{frontend_css}' type='text/css'/>"
  1135                 ."<title>$title</title>"
  1136                 ."</head>"
  1137               ."<script>"
  1138               .$SetCursorPosition_JS
  1139               ."</script>"
  1140               ."<body onLoad='setCursorPosition(document.all.mytextarea, $cursor_position, $cursor_position+10)'>"
  1141               ."<h1>Журнал лабораторных работ. Правка</h1>"
  1142               ."<form>"
  1143               ."<textarea rows='30' cols='100' wrap='off' id='mytextarea'>$result</textarea>"
  1144               ."<br/><input type='submit' value='Сохранить' label='label'/>"
  1145               ."</form>"
  1146               ."<p>Внимательно правим, потом сохраняем</p>"
  1147               ."<p>Строки, начинающиеся символами #l3: можно трогать, только если точно знаешь, что делаешь</p>"
  1148               ."</body>"
  1149               ."</html>";
  1151     if ($output_filename eq "-") {
  1152         print $result;
  1153     }
  1154     else {
  1155         open(OUT, ">", $output_filename)
  1156             or die "Can't open $output_filename for writing\n";
  1157         binmode ":utf8";
  1158         print OUT "$result";
  1159         close(OUT);
  1160     }
  1161 }
  1163 #############
  1164 # print_all_txt
  1165 #
  1166 # Вывести страницу с текстовым представлением журнала для редактирования
  1167 #
  1168 # In:       $_[0]       output_filename
  1169 # Out:
  1171 sub print_all_txt
  1172 {
  1173     my $result;
  1175     $result = print_command_lines_txt;
  1177     $result =~ s/>/>/g;
  1178     $result =~ s/</</g;
  1179     $result =~ s/&/&/g;
  1181     if ($output_filename eq "-") {
  1182         print $result;
  1183     }
  1184     else {
  1185         open(OUT, ">:utf8", $output_filename)
  1186             or die "Can't open $output_filename for writing\n";
  1187         print OUT "$result";
  1188         close(OUT);
  1189     }
  1190 }
  1193 #############
  1194 # print_all_html
  1195 #
  1196 #
  1197 #
  1198 # In:       $_[0]       output_filename
  1199 # Out:
  1202 sub print_all_html
  1203 {
  1204     my $output_filename=$_[0];
  1206     my $result;
  1207     my ($command_lines,$toc)  = print_command_lines_html;
  1208     my $files_section         = print_files_html;
  1210     $result = $debug_output;
  1211     $result .= print_header_html($toc);
  1214 #    $result.= join " <br/>", keys %Sessions;
  1215 #    for my $sess (keys %Sessions) {
  1216 #            $result .= join " ", keys (%{$Sessions{$sess}});
  1217 #            $result .= "<br/>";
  1218 #    }
  1220     $result.= "<h2 id='log'>Журнал</h2>"       . $command_lines;
  1221     $result.= "<h2 id='files'>Файлы</h2>"      . $files_section if $files_section;
  1222     $result.= "<h2 id='stat'>Статистика</h2>"  . print_stat_html;
  1223     $result.= "<h2 id='help'>Справка</h2>"     . $Html_Help . "<br/>"; 
  1224     $result.= "<h2 id='about'>О программе</h2>". $Html_About. "<br/>"; 
  1225     $result.= print_footer_html;
  1227     if ($output_filename eq "-") {
  1228         binmode STDOUT, ":utf8";
  1229         print $result;
  1230     }
  1231     else {
  1232         open(OUT, ">:utf8", $output_filename)
  1233             or die "Can't open $output_filename for writing\n";
  1234         print OUT $result;
  1235         close(OUT);
  1236     }
  1237 }
  1239 #############
  1240 # print_header_html
  1241 #
  1242 #
  1243 #
  1244 # In:   $_[0]       Содержание
  1245 # Out:              Распечатанный заголовок
  1247 sub print_header_html
  1248 {
  1249     my $toc = $_[0];
  1250     my $course_name = $Config{"course-name"};
  1251     my $course_code = $Config{"course-code"};
  1252     my $course_date = $Config{"course-date"};
  1253     my $course_center = $Config{"course-center"};
  1254     my $course_trainer = $Config{"course-trainer"};
  1255     my $course_student = $Config{"course-student"};
  1257     my $title    = "Журнал лабораторных работ";
  1258     $title      .= " -- ".$course_student if $course_student;
  1259     if ($course_date) {
  1260         $title  .= " -- ".$course_date; 
  1261         $title  .= $course_code ? "/".$course_code 
  1262                                 : "";
  1263     }
  1264     else {
  1265         $title  .= " -- ".$course_code if $course_code;
  1266     }
  1268     # Управляющая форма
  1269     my $control_form .= "<div class='visibility_form' title='Выберите какие элементы должны быть показаны в журнале'>"
  1270                      .  "<span class='header'>Видимые элементы</span>"
  1271                      .  "<span class='window_controls'><a href='' onclick='' title='свернуть форму управления'>_</a> <a href='' onclick='' title='закрыть форму управления'>x</a></span>"
  1272                      .  "<div><form>\n";
  1273     for my $element (sort keys %Elements_Visibility)
  1274     {
  1275         my ($skip, @e) = split /\s+/, $element;
  1276         my $showhide = join "", map { "ShowHide('$_');" } @e ;
  1277         $control_form .= "<div><input type='checkbox' name='$e[0]' onclick=\"$showhide\" checked>".
  1278                 $Elements_Visibility{$element}.
  1279                 "</input></div>";
  1280     }
  1281     $control_form .= "</form>\n"
  1282                   .  "</div>\n";
  1285     # Управляющая форма отключена
  1286     # Она слишком сильно мешает, нужно что-то переделать
  1287     $control_form = "";
  1289     my $tigra_hints_array=tigra_hints_generate;
  1291     my $result;
  1292     $result = <<HEADER;
  1293     <html>
  1294     <head>
  1295     <meta content='text/html; charset=utf-8' http-equiv='Content-Type' />
  1296     <link rel='stylesheet' href='$Config{frontend_css}' type='text/css'/>
  1297     <title>$title</title>
  1298     </head>
  1299     <body>
  1300     <!--<script>
  1301     $Html_JavaScript
  1302     </script>-->
  1304 <!-- vvv Tigra Hints vvv -->
  1305 <script language="JavaScript" src="/tigra/hints.js"></script>
  1306 <!--<script language="JavaScript" src="/tigra/hints_cfg.js"></script>-->
  1307 <script>$tigra_hints_array</script>
  1308 <style>
  1309 /* a class for all Tigra Hints boxes, TD object */
  1310     .hintsClass
  1311         {text-align: left; font-size:80%; font-family: Verdana, Arial, Helvetica; background-color:#ffffee; padding: 0px 0px 0px 0px;}
  1312 /* this class is used by Tigra Hints wrappers */
  1313     .row
  1314         {background: white;}
  1317     .bl2 {border: 1px solid #e68200; background:url(/tigra/block/bl2.gif) 0 100% no-repeat; text-align:left}
  1318     .bl {background:url(/tigra/block/bl2.gif) 0 100% no-repeat; text-align:left}
  1319     .br {background:url(/tigra/block/br2.gif) 100% 100% no-repeat}
  1320     .tl {background:url(/tigra/block/tl2.gif) 0 0 no-repeat}
  1321     .tr {background:url(/tigra/block/tr2.gif) 100% 0 no-repeat; padding:10px}
  1322     .tr2 {background:url(/tigra/block/tr2.gif) 100% 0 no-repeat}
  1323     .t {background:url(/tigra/block/dot2.gif) 0 0 repeat-x}
  1324     .b {background:url(/tigra/block/dot2.gif) 0 100% repeat-x}
  1325     .l {background:url(/tigra/block/dot2.gif) 0 0 repeat-y}
  1326     .r {background:url(/tigra/block/dot2.gif) 100% 0 repeat-y}
  1329 </style>
  1330 <!-- ^^^ Tigra Hints ^^^ -->
  1332 <!--
  1333     .bl2 {border: 1px solid #e68200; background:url(/tigra/block/bl2.gif) 0 100% no-repeat; width:20em; text-align:center}
  1334     .bl {background:url(/tigra/block/bl2.gif) 0 100% no-repeat; width:20em; text-align:center}
  1335     .br {background:url(/tigra/block/br2.gif) 100% 100% no-repeat}
  1336     .tl {background:url(/tigra/block/tl2.gif) 0 0 no-repeat}
  1337     .tr {background:url(/tigra/block/tr2.gif) 100% 0 no-repeat; padding:10px}
  1338     .tr2 {background:url(/tigra/block/tr2.gif) 100% 0 no-repeat}
  1339     .t {background:url(/tigra/block/dot2.gif) 0 0 repeat-x; width:20em}
  1340     .b {background:url(/tigra/block/dot2.gif) 0 100% repeat-x}
  1341     .l {background:url(/tigra/block/dot2.gif) 0 0 repeat-y}
  1342     .r {background:url(/tigra/block/dot2.gif) 100% 0 repeat-y}
  1343 -->
  1346     <div class='edit_link'>
  1347     [ <a href='?action=edit&$filter_url'>править</a> ]
  1348     </div>
  1349     <h1 onmouseover="myHint.show('1')" onmouseout="myHint.hide()" class='lined_header'>Журнал лабораторных работ</h1>
  1350 HEADER
  1351     if (    $course_student 
  1352             || $course_trainer 
  1353             || $course_name 
  1354             || $course_code 
  1355             || $course_date 
  1356             || $course_center) {
  1357             $result .= "<p>";
  1358             $result .= "Выполнил $course_student<br/>"  if $course_student;
  1359             $result .= "Проверил $course_trainer <br/>" if $course_trainer;
  1360             $result .= "Курс "                          if $course_name 
  1361                                                             || $course_code 
  1362                                                             || $course_date;
  1363             $result .= "$course_name "                  if $course_name;
  1364             $result .= "($course_code)"                 if $course_code;
  1365             $result .= ", $course_date<br/>"            if $course_date;
  1366             $result .= "Учебный центр $course_center <br/>" if $course_center;
  1367             $result .= "Фильтр ".join(" ", map("$filter{$_}=$_", keys %filter))."<br/>" if %filter;
  1368             $result .= "</p>";
  1369     }
  1371     $result .= <<HEADER;
  1372     <table width='100%'>
  1373     <tr>
  1374     <td width='*'>
  1376     <table border=0 id='toc' class='toc'>
  1377     <tr>
  1378     <td>
  1379     <div class='toc_title'>Содержание</div>
  1380     <ul>
  1381         <li><a href='#log'>Журнал</a></li>
  1382         <ul>$toc</ul>
  1383         <li><a href='#files'>Файлы</a></li>
  1384         <li><a href='#stat'>Статистика</a></li>
  1385         <li><a href='#help'>Справка</a></li>
  1386         <li><a href='#about'>О программе</a></li>
  1387     </ul>
  1388     </td>
  1389     </tr>
  1390     </table>
  1392     </td>
  1393     <td valign='top' width=200>$control_form</td>
  1394     </tr>
  1395     </table>
  1396 HEADER
  1398     return $result;
  1399 }
  1402 #############
  1403 # print_footer_html
  1404 #
  1405 #
  1406 #
  1407 #
  1408 #
  1410 sub print_footer_html
  1411 {
  1412     return "</body>\n</html>\n";
  1413 }
  1418 #############
  1419 # print_stat_html
  1420 #
  1421 #
  1422 #
  1423 # In:
  1424 # Out:
  1426 sub print_stat_html
  1427 {
  1428     %StatNames = (
  1429         FirstCommand        => "Время первой команды журнала",
  1430         LastCommand         => "Время последней команды журнала",
  1431         TotalCommands       => "Количество командных строк в журнале",
  1432         ErrorsPercentage    => "Процент команд с ненулевым кодом завершения, %",
  1433         MistypesPercentage  => "Процент синтаксически неверно набранных команд, %",
  1434         TotalTime           => "Суммарное время работы с терминалом <sup><font size='-2'>*</font></sup>, час",
  1435         CommandsPerTime     => "Количество командных строк в единицу времени, команда/мин",
  1436         CommandsFrequency   => "Частота использования команд",
  1437         RareCommands        => "Частота использования этих команд < 0.5%",
  1438     );
  1439     @StatOrder = (
  1440         FirstCommand,
  1441         LastCommand,
  1442         TotalCommands,
  1443         ErrorsPercentage,
  1444         MistypesPercentage,
  1445         TotalTime,
  1446         CommandsPerTime,
  1447         CommandsFrequency,
  1448         RareCommands,
  1449     );
  1451     # Подготовка статистики к выводу
  1452     # Некоторые значения пересчитываются!
  1453     # Дальше их лучше уже не использовать!!!
  1455     my %CommandsFrequency = %frequency_of_command;
  1457     $Stat{TotalTime} ||= 0;
  1458     my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($Stat{FirstCommand} || 0);
  1459     $Stat{FirstCommand} = sprintf "%02i:%02i:%02i %04i-%2i-%2i", $hour, $min, $sec,  $year+1900, $mon+1, $mday;
  1460     ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($Stat{LastCommand} || 0);
  1461     $Stat{LastCommand} = sprintf "%02i:%02i:%02i %04i-%2i-%2i", $hour, $min, $sec,  $year+1900, $mon+1, $mday;
  1462     if ($Stat{TotalCommands}) {
  1463         $Stat{ErrorsPercentage} = sprintf "%5.2f", $Stat{ErrorCommands}*100/$Stat{TotalCommands};
  1464         $Stat{MistypesPercentage} = sprintf "%5.2f", $Stat{MistypedCommands}*100/$Stat{TotalCommands};
  1465     }
  1466     $Stat{CommandsPerTime} = sprintf "%5.2f", $Stat{TotalCommands}*60/$Stat{TotalTime}
  1467         if $Stat{TotalTime};
  1468     $Stat{TotalTime} = sprintf "%5.2f", $Stat{TotalTime}/60/60;
  1470     my $total_commands=0;
  1471     for $command (keys %CommandsFrequency){
  1472         $total_commands += $CommandsFrequency{$command};
  1473     }
  1474     if ($total_commands) {
  1475         for $command (reverse sort {$CommandsFrequency{$a} <=> $CommandsFrequency{$b}} keys %CommandsFrequency){
  1476             my $command_html;
  1477             my $percentage = sprintf "%5.2f",$CommandsFrequency{$command}*100/$total_commands;
  1478             if ($percentage < 0.5) {
  1479                 my $hint = make_comment($command);
  1480                 $command_html = "$command";
  1481                 $command_html = "<span title='$hint' class='with_hint'>$command_html</span>" if $hint;
  1482                 $command_html = "<span class='without_hint'>$command_html</span>" if not $hint;
  1483                 my $command_html = "<tt>$command_html</tt>";
  1484                 $Stat{RareCommands} .= $command_html."<sub><font size='-2'>".$CommandsFrequency{$command}."</font></sub> , ";
  1485             }
  1486             else {
  1487                 my $hint = make_comment($command);
  1488                 $command_html = "$command";
  1489                 $command_html = "<span title='$hint' class='with_hint'>$command_html</span>" if $hint;
  1490                 $command_html = "<span class='without_hint'>$command_html</span>" if not $hint;
  1491                 my $command_html = "<tt>$command_html</tt>";
  1492                 $percentage = sprintf "%5.2f",$percentage;
  1493                 $Stat{CommandsFrequency} .= "<tr><td>".$command_html."</td><td>".$CommandsFrequency{$command}."</td>".
  1494                     "<td>|".("="x int($CommandsFrequency{$command}*100/$total_commands))."| $percentage%</td></tr>";
  1495             }
  1496         }
  1497         $Stat{CommandsFrequency} = "<table>".$Stat{CommandsFrequency}."</table>";
  1498         $Stat{RareCommands} =~ s/, $// if $Stat{RareCommands};
  1499     }
  1501     my $result = q();
  1502     for my $stat (@StatOrder) {
  1503         next unless $Stat{"$stat"};
  1504         $result .= "<tr valign='top'><td width='300'>".$StatNames{"$stat"}."</td><td>".$Stat{"$stat"}."</td></tr>"
  1505     }
  1506     $result  = "<table>$result</table>"
  1507              . "<font size='-2'>____<br/>*) Интервалы неактивности длительностью "
  1508              .  ($Config{stat_inactivity_interval}/60)
  1509              . " минут и более не учитываются</font></br>";
  1511     return $result;
  1512 }
  1515 sub collapse_list($)
  1516 {
  1517     my $res = "";
  1518     for my $elem (@{$_[0]}) {
  1519         if (ref $elem eq "ARRAY") {
  1520             $res .= "<ul>".collapse_list($elem)."</ul>";
  1521         }
  1522         else
  1523         {
  1524             $res .= "<li>".$elem."</li>";
  1525         }
  1526     }
  1527     return $res;
  1528 }
  1531 sub print_files_html
  1532 {
  1533     my $result = qq(); 
  1534     my @toc;
  1535     for my $file (sort keys %Files) {
  1536           my $div_id = "file:$file";
  1537           $div_id =~ s@/@_@g;
  1538           push @toc, "<a href='#$div_id'>$file</a>";
  1539           $result .= "<div class='filename' id='$div_id'>".$file."</div>\n"
  1540                   .  "<div class='file_navigation'><a href='#command:".$Files{$file}->{source_command_id}."'>".">"."</a></div>"
  1541                   .  "<div class='filedata'><pre>".$Files{$file}->{content}."</pre></div>";
  1542     }
  1543     if ($result) {
  1544         return "<div class='files_toc'>".collapse_list(\@toc)."</div>".$result;
  1545     } 
  1546     else {
  1547         return "";
  1548     }
  1549 }
  1552 sub init_variables
  1553 {
  1554 $Html_Help = <<HELP;
  1555     Для того чтобы использовать LiLaLo, не нужно знать ничего особенного:
  1556     всё происходит само собой.
  1557     Однако, чтобы ведение и последующее использование журналов
  1558     было как можно более эффективным, желательно иметь в виду следующее:
  1559     <ol>
  1560     <li><p> 
  1561     В журнал автоматически попадают все команды, данные в любом терминале системы.
  1562     </p></li>
  1563     <li><p>
  1564     Для того чтобы убедиться, что журнал на текущем терминале ведётся, 
  1565     и команды записываются, дайте команду w.
  1566     В поле WHAT, соответствующем текущему терминалу, 
  1567     должна быть указана программа script.
  1568     </p></li>
  1569     <li><p>
  1570     Команды, при наборе которых были допущены синтаксические ошибки, 
  1571     выводятся перечёркнутым текстом:
  1572 <table>
  1573 <tr class='command'>
  1574 <td class='script'>
  1575 <pre class='_mistyped_cline'>
  1576 \$ l s-l</pre>
  1577 <pre class='_mistyped_output'>bash: l: command not found
  1578 </pre>
  1579 </td>
  1580 </tr>
  1581 </table>
  1582 <br/>
  1583     </p></li>
  1584     <li><p>
  1585     Если код завершения команды равен нулю, 
  1586     команда была выполнена без ошибок.
  1587     Команды, код завершения которых отличен от нуля, выделяются цветом.
  1588 <table>
  1589 <tr class='command'>
  1590 <td class='script'>
  1591 <pre class='_wrong_cline'>
  1592 \$ test 5 -lt 4</pre>
  1593 </pre>
  1594 </td>
  1595 </tr>
  1596 </table>
  1597     Обратите внимание на то, что код завершения команды может быть отличен от нуля
  1598     не только в тех случаях, когда команда была выполнена с ошибкой.
  1599     Многие команды используют код завершения, например, для того чтобы показать результаты проверки
  1600 <br/>
  1601     </p></li>
  1602     <li><p>
  1603     Команды, ход выполнения которых был прерван пользователем, выделяются цветом.
  1604 <table>
  1605 <tr class='command'>
  1606 <td class='script'>
  1607 <pre class='_interrupted_cline'>
  1608 \$ find / -name abc</pre>
  1609 <pre class='interrupted_output'>find: /home/devi-orig/.gnome2: Keine Berechtigung
  1610 find: /home/devi-orig/.gnome2_private: Keine Berechtigung
  1611 find: /home/devi-orig/.nautilus/metafiles: Keine Berechtigung
  1612 find: /home/devi-orig/.metacity: Keine Berechtigung
  1613 find: /home/devi-orig/.inkscape: Keine Berechtigung
  1614 ^C
  1615 </pre>
  1616 </td>
  1617 </tr>
  1618 </table>
  1619 <br/>
  1620     </p></li>
  1621     <li><p>
  1622     Команды, выполненные с привилегиями суперпользователя,
  1623     выделяются слева красной чертой.
  1624 <table>
  1625 <tr class='command'>
  1626 <td class='script'>
  1627 <pre class='_root_cline'>
  1628 # id</pre>
  1629 <pre class='_root_output'>
  1630 uid=0(root) gid=0(root) Gruppen=0(root)
  1631 </pre>
  1632 </td>
  1633 </tr>
  1634 </table>
  1635     <br/>
  1636     </p></li>
  1637     <li><p>
  1638     Изменения, внесённые в текстовый файл с помощью редактора, 
  1639     запоминаются и показываются в журнале в формате ed.
  1640     Строки, начинающиеся символом "<", удалены, а строки,
  1641     начинающиеся символом ">" -- добавлены.
  1642 <table>
  1643 <tr class='command'>
  1644 <td class='script'>
  1645 <pre class='cline'>
  1646 \$ vi ~/.bashrc</pre>
  1647 <table><tr><td width='5'/><td class='diff'><pre>2a3,5
  1648 >    if [ -f /usr/local/etc/bash_completion ]; then
  1649 >         . /usr/local/etc/bash_completion
  1650 >        fi
  1651 </pre></td></tr></table></td>
  1652 </tr>
  1653 </table>
  1654     <br/>
  1655     </p></li>
  1656     <li><p>
  1657     Для того чтобы изменить файл в соответствии с показанными в диффшоте
  1658     изменениями, можно воспользоваться командой patch.
  1659     Нужно скопировать изменения, запустить программу patch, указав в
  1660     качестве её аргумента файл, к которому применяются изменения,
  1661     и всавить скопированный текст:
  1662 <table>
  1663 <tr class='command'>
  1664 <td class='script'>
  1665 <pre class='cline'>
  1666 \$ patch ~/.bashrc</pre>
  1667 </td>
  1668 </tr>
  1669 </table>
  1670     В данном случае изменения применяются к файлу ~/.bashrc
  1671     </p></li>
  1672     <li><p>
  1673     Для того чтобы получить краткую справочную информацию о команде, 
  1674     нужно подвести к ней мышь. Во всплывающей подсказке появится краткое
  1675     описание команды.
  1676     </p>
  1677     <p>
  1678     Если справочная информация о команде есть, 
  1679     команда выделяется голубым фоном, например: <span class="with_hint" title="главный текстовый редактор Unix">vi</span>.
  1680     Если справочная информация отсутствует,
  1681     команда выделяется розовым фоном, например: <span class="without_hint">notepad.exe</span>.
  1682     Справочная информация может отсутствовать в том случае, 
  1683     если (1) команда введена неверно; (2) если распознавание команды LiLaLo выполнено неверно;
  1684     (3) если информация о команде неизвестна LiLaLo.
  1685     Последнее возможно для редких команд.
  1686     </p></li>
  1687     <li><p>
  1688     Большие, в особенности многострочные, всплывающие подсказки лучше 
  1689     всего показываются браузерами KDE Konqueror, Apple Safari и Microsoft Internet Explorer.
  1690     В браузерах Mozilla и Firefox они отображаются не полностью, 
  1691     а вместо перевода строки выводится специальный символ.
  1692     </p></li>
  1693     <li><p>
  1694     Время ввода команды, показанное в журнале, соответствует времени 
  1695     <i>начала ввода командной строки</i>, которое равно тому моменту, 
  1696     когда на терминале появилось приглашение интерпретатора
  1697     </p></li>
  1698     <li><p>
  1699     Имя терминала, на котором была введена команда, показано в специальном блоке.
  1700     Этот блок показывается только в том случае, если терминал
  1701     текущей команды отличается от терминала предыдущей.
  1702     </p></li>
  1703     <li><p>
  1704     Вывод не интересующих вас в настоящий момент элементов журнала,
  1705     таких как время, имя терминала и других, можно отключить.
  1706     Для этого нужно воспользоваться <a href='#visibility_form'>формой управления журналом</a>
  1707     вверху страницы.
  1708     </p></li>
  1709     <li><p>
  1710     Небольшие комментарии к командам можно вставлять прямо из командной строки.
  1711     Комментарий вводится прямо в командную строку, после символов #^ или #v.
  1712     Символы ^ и v показывают направление выбора команды, к которой относится комментарий:
  1713     ^ - к предыдущей, v - к следующей.
  1714     Например, если в командной строке было введено:
  1715 <pre class='cline'>
  1716 \$ whoami
  1717 </pre>
  1718 <pre class='output'>
  1719 user
  1720 </pre>
  1721 <pre class='cline'>
  1722 \$ #^ Интересно, кто я?
  1723 </pre>
  1724     в журнале это будет выглядеть так:
  1726 <pre class='cline'>
  1727 \$ whoami
  1728 </pre>
  1729 <pre class='output'>
  1730 user
  1731 </pre>
  1732 <table class='note'><tr><td width='100%' class='note_text'>
  1733 <tr> <td> Интересно, кто я?<br/> </td></tr></table> 
  1734     </p></li>
  1735     <li><p>
  1736     Если комментарий содержит несколько строк,
  1737     его можно вставить в журнал следующим образом:
  1738 <pre class='cline'>
  1739 \$ whoami
  1740 </pre>
  1741 <pre class='output'>
  1742 user
  1743 </pre>
  1744 <pre class='cline'>
  1745 \$ cat > /dev/null #^ Интересно, кто я?
  1746 </pre>
  1747 <pre class='output'>
  1748 Программа whoami выводит имя пользователя, под которым 
  1749 мы зарегистрировались в системе.
  1750 -
  1751 Она не может ответить на вопрос о нашем назначении 
  1752 в этом мире.
  1753 </pre>
  1754     В журнале это будет выглядеть так:
  1755 <table>
  1756 <tr class='command'>
  1757 <td class='script'>
  1758 <pre class='cline'>
  1759 \$ whoami</pre>
  1760 <pre class='output'>user
  1761 </pre>
  1762 <table class='note'><tr><td class='note_title'>Интересно, кто я?</td></tr><tr><td width='100%' class='note_text'>
  1763 Программа whoami выводит имя пользователя, под которым<br/>
  1764 мы зарегистрировались в системе.<br/>
  1765 <br/>
  1766 Она не может ответить на вопрос о нашем назначении<br/>
  1767 в этом мире.<br/>
  1768 </td></tr></table>
  1769 </td>
  1770 </tr>
  1771 </table>
  1772     Для разделения нескольких абзацев между собой
  1773     используйте символ "-", один в строке.
  1774     <br/>
  1775 </p></li>
  1776     <li><p>
  1777     Комментарии, не относящиеся непосредственно ни к какой из команд, 
  1778     добавляются точно таким же способом, только вместо симолов #^ или #v 
  1779     нужно использовать символы #=
  1780     </p></li>
  1782     <p><li>
  1783     Содержимое файла может быть показано в журнале.
  1784     Для этого его нужно вывести с помощью программы cat.
  1785     Если вывод команды отметить симоволами #!, 
  1786     содержимое файла будет показано в журнале
  1787     в специально отведённой для этого секции.
  1788     </li></p>
  1790     <p>
  1791     <li>
  1792     Для того чтобы вставить скриншот интересующего вас окна в журнал,
  1793     нужно воспользоваться командой l3shot.
  1794     После того как команда вызвана, нужно с помощью мыши выбрать окно, которое
  1795     должно быть в журнале.
  1796     </li>
  1797     </p>
  1799     <p>
  1800     <li>
  1801     Команды в журнале расположены в хронологическом порядке.
  1802     Если две команды давались одна за другой, но на разных терминалах,
  1803     в журнале они будут рядом, даже если они не имеют друг к другу никакого отношения.
  1804 <pre>
  1805 1
  1806     2
  1807 3   
  1808     4
  1809 </pre>
  1810     Группы команд, выполненных на разных терминалах, разделяются специальной линией.
  1811     Под этой линией в правом углу показано имя терминала, на котором выполнялись команды.
  1812     Для того чтобы посмотреть команды только одного сенса, 
  1813     нужно щёкнуть по этому названию.
  1814     </li>
  1815     </p>
  1816 </ol>
  1817 HELP
  1819 $Html_About = <<ABOUT;
  1820     <p>
  1821     <a href='http://xgu.ru/lilalo/'>LiLaLo</a> (L3) расшифровывается как Live Lab Log.<br/>
  1822     Программа разработана для повышения эффективности обучения Unix/Linux-системам.<br/>
  1823     (c) Игорь Чубин, 2004-2008<br/>
  1824     </p>
  1825 ABOUT
  1826 $Html_About.='$Id$ </p>';
  1828 $Html_JavaScript = <<JS;
  1829     function getElementsByClassName(Class_Name)
  1830     {
  1831         var Result=new Array();
  1832         var All_Elements=document.all || document.getElementsByTagName('*');
  1833         for (i=0; i<All_Elements.length; i++)
  1834             if (All_Elements[i].className==Class_Name)
  1835         Result.push(All_Elements[i]);
  1836         return Result;
  1837     }
  1838     function ShowHide (name)
  1839     {
  1840         elements=getElementsByClassName(name);
  1841         for(i=0; i<elements.length; i++)
  1842             if (elements[i].style.display == "none")
  1843                 elements[i].style.display = "";
  1844             else
  1845                 elements[i].style.display = "none";
  1846             //if (elements[i].style.visibility == "hidden")
  1847             //  elements[i].style.visibility = "visible";
  1848             //else
  1849             //  elements[i].style.visibility = "hidden";
  1850     }
  1851     function filter_by_output(text)
  1852     {
  1854         var jjj=0;
  1856         elements=getElementsByClassName('command');
  1857         for(i=0; i<elements.length; i++) {
  1858             subelems = elements[i].getElementsByTagName('pre');
  1859             for(j=0; j<subelems.length; j++) {
  1860                 if (subelems[j].className = 'output') {
  1861                     var str = new String(subelems[j].nodeValue);
  1862                     if (jjj != 1) { 
  1863                         alert(str);
  1864                         jjj=1;
  1865                     }
  1866                     if (str.indexOf(text) >0) 
  1867                         subelems[j].style.display = "none";
  1868                     else
  1869                         subelems[j].style.display = "";
  1871                 }
  1873             }
  1874         }       
  1876     }
  1877 JS
  1879 $SetCursorPosition_JS = <<JS;
  1880 function setCursorPosition(oInput,oStart,oEnd) {
  1881     oInput.focus();
  1882     if( oInput.setSelectionRange ) {
  1883         oInput.setSelectionRange(oStart,oEnd);
  1884     } else if( oInput.createTextRange ) {
  1885         var range = oInput.createTextRange();
  1886         range.collapse(true);
  1887         range.moveEnd('character',oEnd);
  1888         range.moveStart('character',oStart);
  1889         range.select();
  1890     }
  1891 }
  1892 JS
  1894 %Search_Machines = (
  1895         "google" =>     {   "query" =>  "http://www.google.com/search?q=" ,
  1896                     "icon"  =>  "$Config{frontend_google_ico}" },
  1897         "freebsd" =>    {   "query" =>  "http://www.freebsd.org/cgi/man.cgi?query=",
  1898                     "icon"  =>  "$Config{frontend_freebsd_ico}" },
  1899         "linux"  =>     {   "query" =>  "http://man.he.net/?topic=",
  1900                     "icon"  =>  "$Config{frontend_linux_ico}"},
  1901         "opennet"  =>   {   "query" =>  "http://www.opennet.ru/search.shtml?words=",
  1902                     "icon"  =>  "$Config{frontend_opennet_ico}"},
  1903         "local" =>  {   "query" =>  "http://www.freebsd.org/cgi/man.cgi?query=",
  1904                     "icon"  =>  "$Config{frontend_local_ico}" },
  1906     );
  1908 %Elements_Visibility = (
  1909         "0 new_commands_table"      =>  "новые команды",
  1910         "1 diff"      =>  "редактор",
  1911         "2 time"      =>  "время",
  1912         "3 ttychange"     =>  "терминал",
  1913         "4 wrong_output wrong_cline wrong_root_output wrong_root_cline" 
  1914                 =>  "команды с ненулевым кодом завершения",
  1915         "5 mistyped_output mistyped_cline mistyped_root_output mistyped_root_cline" 
  1916                 =>  "неверно набранные команды",
  1917         "6 interrupted_output interrupted_cline interrupted_root_output interrupted_root_cline" 
  1918                 =>  "прерванные команды",
  1919         "7 tab_completion_output tab_completion_cline"    
  1920                 =>  "продолжение с помощью tab"
  1921 );
  1923 @Day_Name      = qw/ Воскресенье Понедельник Вторник Среда Четверг Пятница Суббота /;
  1924 @Month_Name    = qw/ Январь Февраль Март Апрель Май Июнь Июль Август Сентябрь Октябрь Ноябрь Декабрь /;
  1925 @Of_Month_Name = qw/ Января Февраля Марта Апреля Мая Июня Июля Августа Сентября Октября Ноября Декабря /;
  1926 }
  1931 # Временно удалённый код
  1932 # Возможно, он не понадобится уже никогда
  1935 sub search_by
  1936 {
  1937     my $sm = shift;
  1938     my $topic = shift;
  1939     $topic =~ s/ /+/;
  1941     return "<a href='". $Search_Machines{$sm}->{"query"}."$topic'><img width='16' height='16' src='".
  1942                 $Search_Machines{$sm}->{"icon"}."' border='0'/></a>";
  1943 }
  1948 ########################################################################################
  1949 #
  1950 # mywi
  1951 #
  1952 # 
  1953 #
  1954 #
  1955 #
  1956 #
  1957 #
  1961 sub mywi_init
  1962 {
  1963     our $MyWiFile = "/home/devi/mywi/mywi.txt";
  1964     our $MyWiLog = "/home/devi/mywi/mywi.log";
  1965     our $section="";
  1967     our @MywiTXT;       # Массив текстовых записей mywi
  1968     our %MywiHASH;      # Хэш массивов записей
  1969     our %Query;
  1971     load_mywitxt($MyWiFile, \@MywiTXT, \%MywiHASH);
  1972 }
  1974 sub mywi_process_query($)
  1975 #
  1976 # Сделать подсказку по заданному запросу
  1977 # $_[0] - тема для подсказки
  1978 # 
  1979 # Возвращает:
  1980 #   строку-подсказку
  1981 #
  1982 {
  1983     my $query = shift;
  1984     parse_query($query, \%Query);
  1985     $result = search_in_txt(\%Query, \@MywiTXT, \%MywiHASH);
  1987     if (!$result) {
  1988         #add_to_log(\%Query, $MyWiLog);
  1989         return "$query nothing appropriate.  Logged. ".join (";",%Query);
  1990     }   
  1992     return $result;
  1993 }
  1995 ####################################################################################
  1996 #                                   private section
  1997 ####################################################################################
  1999 sub load_mywitxt
  2000 #
  2001 # Загрузить файл с записями Mywi_TXT
  2002 # в массив
  2003 # $_[0] - указатель на массив для загрузки
  2004 # $_[1] - имя файла для загрузки
  2005 # 
  2006 {
  2007     my $MyWiFile = $_[0];
  2008     my $MywiTXT = $_[1];
  2009     my $MywiHASH = $_[2];
  2011     open (MW, "$MyWiFile") or die "Can't open $MyWiFile for reading";
  2012     binmode MW, ":utf8";
  2013     @{$MywiTXT} = <MW>;
  2014     close (MWF);
  2016     for my $mywi_line (@{$MywiTXT}) {
  2017         my $topic = $mywi_line;
  2018         $topic =~ s@\s*\(.*\n@@;
  2019         push @{$$MywiHASH{"$topic"}}, $mywi_line;
  2020 #        $MywiHASH{"$topic"} .= $mywi_line;
  2021     }
  2022 }
  2024 sub parse_query
  2025 #
  2026 # Строка запроса:
  2027 #   [format:]topic[(section)]
  2028 # Элементы format и topic являются не обязательными
  2029 #
  2030 # $_[0] - строка запроса
  2031 # $_[1] - ссылка на хэш запроса
  2032 #
  2033 {
  2034     my $query_string = shift;
  2035     my $query_hash = shift;
  2037     %{$query_hash} = (
  2038         "format"    =>  "txt",
  2039         "section"   =>  "",
  2040         "topic" =>  "",
  2041     );
  2043     if ($query_string =~ s/^([^:]*)://) {
  2044         $query_hash->{"format"} = $1 || "txt";
  2045     }
  2046     if ($query_string =~ s/\(([^(]*)\)$//) {
  2047         $query_hash->{"section"} = $1 || "";
  2048     }
  2049     $query_hash->{"topic"} = $query_string;
  2050 }
  2053 sub search_in_txt
  2054 #
  2055 # Выполнить поиск в текстовой базе 
  2056 # по известному запросу
  2057 # $_[0] -- ссылка на хэш запроса
  2058 # $_[1] -- ссылка на массив текстовых записей
  2059 # $_[2] -- ссылка на хэш массивов текстовых записей
  2060 # Результат:
  2061 #   найденная текстовая запись в заданном формате
  2062 #
  2063 {
  2064     my %Query = %{$_[0]};
  2065     my %MywiHASH = %{$_[2]};
  2067     my $topic = $Query{"topic"};
  2068     my $section = $Query{"section"};
  2069     my $result = "";
  2071     return join("\n",@{$MywiHASH{"$topic"}})."\n";
  2073     for my $l (@{$$_[2]{$topic}}) {
  2074 #    for my $l (@{$_[1]}) {
  2075         my $line = $l;
  2076         if (
  2077             ($section and $line =~ /^\s*\Q$topic\E\s*\($section*\)\s*-/ )
  2078             or (not $section and $line =~ /^\s*\Q$topic\E\s*(\([^)]*\)?)\s*-/) ) {
  2079             $line =~ s/^.* -//mg if ($Config{"short"});
  2080             $result .= "<para>$line</para>";
  2081         }
  2082     }
  2083     return $result;
  2084 }
  2087 sub add_to_log($$)
  2088 #
  2089 # Если в базе отсутствует информация по данной теме, 
  2090 # сделать предположение доступным способом
  2091 # и добавить его в базу
  2092 # или просто сделать отметку о необходимости 
  2093 # расширения базы
  2094 #
  2095 # Добавить запись в журнал
  2096 # $_[0] - запись (ссылка на хэш)
  2097 # $_[1] - имя файла-журнала
  2098 #
  2099 {
  2100     my $query = $_[0];
  2101     my $MyWiLog = $_[1];
  2103     open (MWF, ">>:utf8", $MyWiLog) or die "Can't open $MyWiLog for writing";
  2104     my $my_guess = mywi_guess($query);
  2105     print MWF "$my_guess\n";
  2106     close(MWF);
  2107 }
  2109 sub mywi_guess($)
  2110 # Сформировать исходную строку для журнала по заданному запросу
  2111 # Если секция принадлежит 0..9, в качестве основы для результирующего текста использовать whatis
  2112 # $_[0] - запись (ссылка на хэш)
  2113 # 
  2114 # Возвращает:
  2115 #   строку-предположение
  2116 {
  2117     my %query = %{$_[0]};
  2119     my $topic = $query{"topic"};
  2120     my $section = $query{"section"};
  2122     my $result = "$topic($section)";
  2123     if (!$section or $section =~ /^[1-9]$/)
  2124     {
  2125         # Запрос из категории 1-9
  2126         # Об этом может знать whatis
  2127         $result = `LANG=C whatis -- "$topic"`;
  2128         if ($result =~ /nothing appropriate/i) {
  2129             $result = $topic;
  2130             $result .= "($section)" if $section;
  2131         }
  2132         else {
  2133             1 while ($result =~ s/(\s+)-(\s+)/$1+$2/sg);
  2134             $result =~ s/\s+\(/(/;
  2135             chomp $result;
  2136         }
  2137     }   
  2138     return $result;
  2139 }
