#!/usr/bin/perl use POSIX qw(strftime); use lib '/etc/lilalo'; use l3config; use utf8; our @Command_Lines; our @Command_Lines_Index; our %Commands_Description; our %Args_Description; our %Sessions; our %Uploads; our $debug_output=""; # Используйте эту переменную, если нужно передать отладочную информацию our %filter; our $filter_url; sub init_filter; our %Files; # vvv Инициализация переменных выполняется процедурой init_variables our @Day_Name; our @Month_Name; our @Of_Month_Name; our %Search_Machines; our %Elements_Visibility; # ^^^ our $First_Command=$0; our $Last_Command=40; our %Stat; our %frequency_of_command; # Сколько раз в журнале встречается какая команда our $table_number=1; our %tigra_hints; my %mywi_cache_for; # Кэш для экономии обращений к mywi sub count_frequency_of_commands; sub make_comment; sub make_new_entries_table; sub load_command_lines_from_xml; sub load_sessions_from_xml; sub load_uploads; sub sort_command_lines; sub process_command_lines; sub init_variables; sub main; sub collapse_list($); sub minutes_passed; sub print_all_txt; sub print_all_html; sub print_edit_all_html; sub print_command_lines_html; sub print_command_lines_txt; sub print_files_html; sub print_stat_html; sub print_header_html; sub print_footer_html; sub tigra_hints_generate; #### mywi # sub mywi_init; sub load_mywitxt; sub mywi_process_query($); # sub add_to_log($$); sub parse_query; sub search_in_txt; sub add_to_log($$); sub mywi_guess($); # main(); sub main { $| = 1; init_variables(); init_config(); $Config{frontend_ico_path}=$Config{frontend_css}; $Config{frontend_ico_path}=~s@/[^/]*$@@; init_filter(); mywi_init(); load_command_lines_from_xml($Config{"backend_datafile"}); load_uploads($Config{"upload_dir"}); load_sessions_from_xml($Config{"backend_datafile"}); sort_command_lines; process_command_lines; if (defined($filter{action}) && $filter{action} eq "edit") { print_edit_all_html($Config{"output"}); } else { print_all_html($Config{"output"}); } } sub init_filter { if ($Config{filter}) { # Инициализация фильтра for (split /;;/,$Config{filter}) { my ($var, $val) = split /::/; $filter{$var} = $val || ""; } } $filter_url = join (";;", map("$_::$filter{$_}", keys %filter)); } # extract_from_cline # In: $what = commands | args # Out: return ссылка на хэш, содержащий результаты разбора # команда => позиция # Разобрать командную строку $_[1] и возвратить хэш, содержащий # номер первого появление команды в строке: # команда => первая позиция sub extract_from_cline { my $what = $_[0]; my $cline = $_[1]; my @lists = split /\;/, $cline; my @command_lines = (); for my $command_list (@lists) { push(@command_lines, split(/\|/, $command_list)); } my %position_of_command; my %position_of_arg; my $i=0; for my $command_line (@command_lines) { $command_line =~ s@^\s*@@; $command_line =~ /\s*(\S+)\s*(.*)/; if ($1 && $1 eq "sudo" ) { $position_of_command{"$1"}=$i++; $command_line =~ s/\s*sudo\s+//; } if ($command_line !~ m@^\s*\S*/etc/@) { $command_line =~ s@^\s*\S+/@@; } $command_line =~ /\s*(\S+)\s*(.*)/; my $command = $1; my $args = $2; if ($command && !defined $position_of_command{"$command"}) { $position_of_command{"$command"}=$i++; }; if ($args) { my @args = split (/\s+/, $args); for my $a (@args) { $position_of_arg{"$a"}=$i++ if !defined $position_of_arg{"$a"}; }; } } if ($what eq "commands") { return \%position_of_command; } else { return \%position_of_arg; } } sub mywrap($) { return '
'.$_[0]. '
'; } sub tigra_hints_generate { my $tigra_hints_items=""; for my $hint_id (keys %tigra_hints) { $tigra_hints{$hint_id} =~ s@\n@
@gs; $tigra_hints{$hint_id} =~ s@ - @ — @gs; $tigra_hints{$hint_id} =~ s@'@\\'@gs; # $tigra_hints_items .= "'$hint_id' : mywrap('".$tigra_hints{$hint_id}."'),"; $tigra_hints_items .= "'$hint_id' : '".mywrap($tigra_hints{$hint_id})."',"; } $tigra_hints_items =~ s/,$//; return <
'+s_+ '
'; } TIGRA $a=<; close(CLASS); for $command ($data =~ m@(.*?)@sg) { my %cl; while ($command =~ m@<([^>]*?)>(.*?)@sg) { $cl{$1} = $2; } push @Command_Lines, \%cl; } } sub load_sessions_from_xml { my $datafile = $_[0]; open (CLASS, $datafile) or die "Can't open file with xml lablog ",$datafile,"\n"; local $/; binmode CLASS, ":utf8"; my $data = ; close(CLASS); my $i=0; for my $session ($data =~ m@(.*?)@msg) { my %session_hash; while ($session =~ m@<([^>]*?)>(.*?)@sg) { $session_hash{$1} = $2; } $Sessions{$session_hash{local_session_id}} = \%session_hash; } } sub load_uploads($) { $dir=$_[0]; for $i (glob("$dir/*.png")) { $i =~ s@.*/(([0-9-]+)_([0-9]+).*)@$1@; $Uploads{$2}{$3}=$i; } } #for $key (sort keys %session) { # for $t (sort { $a <=> $b } keys %{ $session{$key} }) { # print $session{$key}{$t}."\n"; # } #} #} # sort_command_lines # In: @Command_Lines # Out: @Command_Lies_Index sub sort_command_lines { my @index; for (my $i=0;$i<=$#Command_Lines;$i++) { $index[$i]=$i; } @Command_Lines_Index = sort { $Command_Lines[$index[$a]]->{"time"} <=> $Command_Lines[$index[$b]]->{"time"} } @index; } ################## # process_command_lines # # Обрабатываются командные строки @Command_Lines # Для каждой строки определяется: # class класс # note комментарий # # In: @Command_Lines_Index # In-Out: @Command_Lines sub process_command_lines { my $current_command=0; my $prev_i; my $tab_seq =0 ; # номер команды в последовательности tab-completion # отличен от нуля только для тех последовательностей, # где постоянно нажимается клавиша tab COMMAND_LINE_PROCESSING: for my $i (@Command_Lines_Index) { $current_command++; next if $current_command < $Config{"start_from_command"}; last if $current_command > $Config{"start_from_command"} + $Config{"commands_to_show_at_a_go"}; my $cl = \$Command_Lines[$i]; # Запоминаем предыщуюу команду # Она нам потребуется, в частности, для ввода tab_seq рпи обработке tab_completion my $prev_cl; $prev_cl = \$Command_Lines[$prev_i] if defined($prev_i); $prev_i = $i; next if !$cl; for my $filter_key (keys %filter) { next COMMAND_LINE_PROCESSING if defined($$cl->{local_session_id}) && defined($Sessions{$$cl->{local_session_id}}->{$filter_key}) && $Sessions{$$cl->{local_session_id}}->{$filter_key} ne $filter{$filter_key}; } $$cl->{id} = $$cl->{"time"}; $$cl->{err} ||=0; # Класс команды $$cl->{"class"} = $$cl->{"err"} eq 130 ? "interrupted" : $$cl->{"err"} eq 127 ? "mistyped" : $$cl->{"err"} ? "wrong" : "normal"; if ($$cl->{"cline"} && $$cl->{"cline"} =~ /[^|`]\s*sudo/ || $$cl->{"uid"} eq 0) { $$cl->{"class"}.="_root"; } my $hint; count_frequency_of_commands($$cl->{"cline"}); $hint = make_comment($$cl->{"cline"}); if ($hint) { $$cl->{hint} = $hint; } $tigra_hints{$$cl->{"time"}} = $hint; #$$cl->{hint}=""; # Выводим верхних строк # и нижних строк, # если эти параметры существуют my $output=""; if ($$cl->{"last_command"} eq "cat" && !$$cl->{"err"} && !($$cl->{"cline"} =~ /{"cline"}; $filename =~ s/.*\s+(\S+)\s*$/$1/; $Files{$filename}->{"content"} = $$cl->{"output"}; $Files{$filename}->{"source_command_id"} = $$cl->{"id"} } my @lines = split '\n', $$cl->{"output"}; if (( $Config{"head_lines"} || $Config{"tail_lines"} ) && $#lines > $Config{"head_lines"} + $Config{"tail_lines"} ) { # for (my $i=0; $i<= $#lines && $i < $Config{"head_lines"}; $i++) { $output .= $lines[$i]."\n"; } $output .= $Config{"skip_text"}."\n"; my $start_line=$#lines-$Config{"tail_lines"}+1; for (my $i=$start_line; $i<= $#lines; $i++) { $output .= $lines[$i]."\n"; } } else { $output = $$cl->{"output"}; } $$cl->{short_output} = $output; # Обработка команд с одинаковым временем # Скорее всего они набраны с помощью tab-completion if (defined($prev_cl)) { if ($$prev_cl->{time} == $$cl->{time} && $$prev_cl->{nonce} == $$cl->{nonce}) { $tab_seq++; } else { $tab_seq=0; }; $$prev_cl->{tab_seq}=$tab_seq; # Обработка команд с одинаковым номером в истории # Скорее всего они набраны с помощью Ctrl-C #if ($$prev_cl->{history} == $$cl->{history}) { # $$prev_cl->{break}=1; #} } #Обработка пометок # Если несколько пометок (notes) идут подряд, # они все объединяются if ($$cl->{cline} =~ /l3shot/) { if ($$cl->{output} =~ m@Screenshot is written to.*/(.*)\.xwd@) { $$cl->{screenshot}="$1".$Config{l3shot_suffix}; } } if ($$cl->{cline} =~ /l3upload/) { if ($$cl->{output} =~ m@Uploaded file name is (.*)@) { $$cl->{screenshot}="$1"; } } if ($$cl->{cline}=~ m@cat[^#]*#([\^=v])\s*(.*)@) { my $note_operator = $1; my $note_title = $2; if ($note_operator eq "=") { $$cl->{"class"} = "note"; $$cl->{"note"} = $$cl->{"output"}; $$cl->{"note_title"} = $2; } else { my $j = $i; if ($note_operator eq "^") { $j--; $j-- while ($j >=0 && (!$Command_Lines[$j] || $Command_Lines[$j]->{tty} ne $$cl->{tty})); } elsif ($note_operator eq "v") { $j++; $j++ while ($j <= @Command_Lines && (!$Command_Lines[$j] || $Command_Lines[$j]->{tty} ne $$cl->{tty})); } $Command_Lines[$j]->{note_title}=$note_title; $Command_Lines[$j]->{note}.=$$cl->{output}; $$cl=0; } } elsif ($$cl->{cline}=~ /#([\^=v])(.*)/) { my $note_operator = $1; my $note_text = $2; if ($note_operator eq "=") { $$cl->{"class"} = "note"; $$cl->{"note"} = $note_text; } else { my $j=$i; if ($note_operator eq "^") { $j--; $j-- while ($j >=0 && (!$Command_Lines[$j] || $Command_Lines[$j]->{tty} ne $$cl->{tty})); } elsif ($note_operator eq "v") { $j++; $j++ while ($j <= @Command_Lines && $Command_Lines[$j]->{tty} ne $$cl->{tty} || !$Command_Lines[$j]); } $Command_Lines[$j]->{note}.="$note_text\n"; $$cl=0; } } if ($$cl->{"class"} eq "note") { my $note_html = $$cl->{note}; $note_html = join ("\n", map ("

$_

", split (/-\n/, $note_html))); $note_html =~ s@(http:[a-zA-Z.0-9/?\_%-]*)@$1@g; $note_html =~ s@(www\.[a-zA-Z.0-9/?\_%-]*)@$1@g; $$cl->{"note_html"} = $note_html; } } } =cut Процедура print_command_lines выводит HTML-представление разобранного lab-скрипта. Разобранный lab-скрипт должен находиться в массиве @Command_Lines =cut sub print_command_lines_html { my @toc; # Оглавление my $note_number=0; my $result = q(); my $this_day_resut = q(); my $cl; my $last_tty=""; my $last_session=""; my $last_day=q(); my $last_wday=q(); my $first_command_of_the_day_unix_time=q(); my $human_readable_time=q(); my $in_range=0; my $current_command=0; my @known_commands; $Stat{LastCommand} ||= 0; $Stat{TotalCommands} ||= 0; $Stat{ErrorCommands} ||= 0; $Stat{MistypedCommands} ||= 0; my %new_entries_of = ( "1 1" => "программы пользователя", "2 8" => "программы администратора", "3 sh" => "команды интерпретатора", "4 script"=> "скрипты", ); COMMAND_LINE: for my $k (@Command_Lines_Index) { my $cl=$Command_Lines[$Command_Lines_Index[$current_command++]]; next unless $cl; my $next_cl=$Command_Lines[$Command_Lines_Index[$current_command+1]]; next if $current_command < $Config{"start_from_command"}; last if $current_command > $Config{"start_from_command"} + $Config{"commands_to_show_at_a_go"}; # Пропускаем строки, которые противоречат фильтру # Если у нас недостаточно информации о том, подходит строка под фильтр или нет, # мы её выводим for my $filter_key (keys %filter) { next COMMAND_LINE if defined($cl->{local_session_id}) && defined($Sessions{$cl->{local_session_id}}->{$filter_key}) && $Sessions{$cl->{local_session_id}}->{$filter_key} ne $filter{$filter_key}; } # Набираем статистику # Хэш %Stat $Stat{FirstCommand} = $cl->{time} unless $Stat{FirstCommand}; if ($cl->{time} - $Stat{LastCommand} < $Config{stat_inactivity_interval}) { $Stat{TotalTime} += $cl->{time} - $Stat{LastCommand} } my $seconds_since_last_command = $cl->{time} - $Stat{LastCommand}; if ($Stat{LastCommand} > $cl->{time}) { $result .= "Время идёт вспять
"; }; $Stat{LastCommand} = $cl->{time}; $Stat{TotalCommands}++; # Пропускаем строки, выходящие за границу "signature", # при условии, что границы указаны # Пропускаем неправильные/прерванные/другие команды if ($Config{"from"} && $cl->{"cline"} =~ /$Config{"signature"}\s*$Config{"from"}/) { $in_range=1; next; } if ($Config{"to"} && $cl->{"cline"} =~ /$Config{"signature"}\s*$Config{"to"}/) { $in_range=0; next; } next if ($Config{"from"} && $Config{"to"} && !$in_range) || ($Config{"skip_empty"} =~ /^y/i && $cl->{"cline"} =~ /^\s*$/ ) || ($Config{"skip_wrong"} =~ /^y/i && $cl->{"err"} != 0) || ($Config{"skip_interrupted"} =~ /^y/i && $cl->{"err"} == 130); # ## ## Начинается собственно вывод ## # ### Сначала обрабатываем границы разделов ### Если тип команды "note", это граница if ($cl->{class} eq "note") { $this_day_result .= "" . "

".$cl->{note_title}."

" if $cl->{note_title} . "".$cl->{note_html}."

"; if ($cl->{note_title}) { push @{$toc[@toc]},"".$cl->{note_title}.""; $note_number++; } next; } my ($sec,$min,$hour,$day,$mon,$year,$wday,$yday,$isdst) = localtime($cl->{time}); # Добавляем спереди 0 для удобочитаемости $min = "0".$min if $min =~ /^.$/; $hour = "0".$hour if $hour =~ /^.$/; $sec = "0".$sec if $sec =~ /^.$/; $class=$cl->{"class"}; $Stat{ErrorCommands}++ if $class =~ /wrong/; $Stat{MistypedCommands}++ if $class =~ /mistype/; # DAY CHANGE if ( $last_day ne $day) { $prev_unix_time=$first_command_of_the_day_unix_time; $first_command_of_the_day_unix_time = $cl->{time}; $human_readable_time = strftime "%D", localtime($prev_unix_time); if ($last_day) { # Вычисляем разность множеств. # Что-то вроде этого, если бы так можно было писать: # @new_commands = keys %frequency_of_command - @known_commands; # Выводим предыдущий день $result .= "

".$Day_Name[$last_wday]." ($human_readable_time)

"; for my $entry_class (sort keys %new_entries_of) { my $table_caption = "Таблица ".$table_number++.".".$Day_Name[$last_wday] .". Новые ".$new_entries_of{$entry_class}; my $new_commands_section = make_new_entries_table( $table_caption, $entry_class=~/[0-9]+\s+(.*)/, \@known_commands); } @known_commands = keys %frequency_of_command; $result .= $this_day_result; } # Добавляем текущий день в оглавление $human_readable_time = strftime "%D", localtime($first_command_of_the_day_unix_time); push @toc, "".$Day_Name[$wday]." ($human_readable_time)\n"; $last_day=$day; $last_wday=$wday; $this_day_result = q(); } else { $this_day_result .= minutes_passed($seconds_since_last_command); } $this_day_result .= "
\n"; # CONSOLE CHANGE if ($cl->{"tty"} && $last_tty ne $cl->{"tty"} && 0) { my $tty = $cl->{"tty"}; $this_day_result .= "
" . $tty ."
"; $last_tty=$cl->{"tty"}; } # Session change if ( $last_session ne $cl->{"local_session_id"}) { my $tty; if (defined $Sessions{$cl->{"local_session_id"}}->{"tty"}) { $this_day_result .= ""; } $last_session=$cl->{"local_session_id"}; } # TIME if ($Config{"show_time"} =~ /^y/i) { $this_day_result .= "
$hour:$min:$sec
" } # COMMAND my $cline; $prompt_hint = join (" ", map("$_=$cl->{$_}", grep (!/^(output|short_output|diff)$/, sort(keys(%{$cl}))))); $cl->{"prompt"} =~ s/ $//; $cline = "".$cl->{"prompt"}."" ."{time}."')\" onmouseout=\"myHint.hide()\">".$cl->{"cline"}.""; $cline =~ s/\n//; if ($cl->{"hint"}) { # $cline = "$cline" ; $cline = "$cline" ; } else { $cline = "$cline"; } $this_day_result .= "
\n
\n"; $this_day_result .= "
" . $cline ; #cline $this_day_result .= "\n" . "\n" . "\n" if ($cl->{"err"} and not $cl->{tab_seq} and not $cl->{break}); $this_day_result .= "\n" . "\n" . "\n" if $cl->{tab_seq}; $this_day_result .= "\n" . "\n" . "\n" if ($cl->{break} and not $cl->{tab_seq}); $this_day_result .= "
\n"; #cline # OUTPUT my $last_command = $cl->{"last_command"}; if (!( $Config{"suppress_editors"} =~ /^y/i && grep ($_ eq $last_command, @{$Config{"editors"}}) || $Config{"suppress_pagers"} =~ /^y/i && grep ($_ eq $last_command, @{$Config{"pagers"}}) || $Config{"suppress_terminal"}=~ /^y/i && grep ($_ eq $last_command, @{$Config{"terminal"}}) )) { $this_day_result .= "
\n" . $cl->{short_output} . "
\n"; } # DIFF $this_day_result .= "
".$cl->{"diff"}."
" if ( $Config{"show_diffs"} =~ /^y/i && $cl->{"diff"}); # SHOT $this_day_result .= join(".", key(%Uploads)); for $t (sort { $a <=> $b } keys %{ $Uploads{$cl->{"local_session_id"}} }) { # if ($t > $cl->{"time"} && $t < $next_cl->{"time"}) { $this_day_result .= "screenshot id ".$cl->{"screenshot"}
                ."" } $this_day_result .= "screenshot id ".$cl->{"screenshot"}
                ."" if ( $Config{"show_screenshots"} =~ /^y/i && $cl->{"screenshot"}); #NOTES if ( $Config{"show_notes"} =~ /^y/i && $cl->{"note"}) { my $note=$cl->{"note"}; $note =~ s/\n/\n/msg; if (not $note =~ s@(http:[a-zA-Z.0-9/_?%-]*)@$1@g) { $note =~ s@(www\.[a-zA-Z.0-9/_?%-]*)@$1@g; }; $this_day_result .= "
"; $this_day_result .= "
".$cl->{note_title}."
" if $cl->{note_title}; $this_day_result .= "
".$note."
"; $this_day_result .= "
\n"; } # Вывод очередной команды окончен $this_day_result .= "
\n"; # cblock $this_day_result .= "
\n" . "
\n"; # command } last: { $prev_unix_time=$first_command_of_the_day_unix_time; $first_command_of_the_day_unix_time = $cl->{time}; $human_readable_time = strftime "%D", localtime($prev_unix_time); $result .= "

".$Day_Name[$last_wday]." ($human_readable_time)

"; for my $entry_class (keys %new_entries_of) { my $table_caption = "Таблица ".$table_number++.".".$Day_Name[$last_wday] . ". Новые ".$new_entries_of{$entry_class}; my $new_commands_section = make_new_entries_table( $table_caption, $entry_class=~/[0-9]+\s+(.*)/, \@known_commands); } @known_commands = keys %frequency_of_command; $result .= $this_day_result; } return ($result, collapse_list (\@toc)); } ############# # make_new_entries_table # # Напечатать таблицу неизвестных команд # # In: $_[0] table_caption # $_[1] entries_class # @_[2..] known_commands # Out: sub make_new_entries_table { my $table_caption; my $entries_class = shift; my @known_commands = @{$_[0]}; my $result = ""; my %count; my @new_commands = (); for my $c (keys %frequency_of_command, @known_commands) { $count{$c}++ } for my $c (keys %frequency_of_command) { push @new_commands, $c if $count{$c} != 2; } my $new_commands_section; if (@new_commands){ my $hint; for my $c (reverse sort { $frequency_of_command{$a} <=> $frequency_of_command{$b} } @new_commands) { $hint = make_comment($c); next unless $hint; my ($command, $hint) = $hint =~ m/(.*?) \s*- \s*(.*)/; next unless $command =~ s/\($entries_class\)//i; $new_commands_section .= "$command$hint"; } } if ($new_commands_section) { $result .= "" . "" . "" . "" . "" . "" . "" . $new_commands_section . "
$table_caption
КомандаОписание
" } return $result; } ############# # minutes_passed # # # # In: $_[0] seconds_since_last_command # Out: "minutes passed" text sub minutes_passed { my $seconds_since_last_command = shift; my $result = ""; if ($seconds_since_last_command > 7200) { my $hours_passed = int($seconds_since_last_command/3600); my $passed_word = $hours_passed % 10 == 1 ? "прошла" : "прошло"; my $hours_word = $hours_passed % 10 == 1 ? "часа": "часов"; $result .= "
" . $passed_word." >".$hours_passed." ".$hours_word . "
\n"; } elsif ($seconds_since_last_command > 600) { my $minutes_passed = int($seconds_since_last_command/60); my $passed_word = $minutes_passed % 100 > 10 && $minutes_passed % 100 < 20 ? "прошло" : $minutes_passed % 10 == 1 ? "прошла" : "прошло"; my $minutes_word = $minutes_passed % 100 > 10 && $minutes_passed % 100 < 20 ? "минут" : $minutes_passed % 10 == 1 ? "минута": $minutes_passed % 10 == 0 ? "минут" : $minutes_passed % 10 > 4 ? "минут" : "минуты"; if ($seconds_since_last_command < 1800) { $result .= "
" . $passed_word." ".$minutes_passed." ".$minutes_word . "
\n"; } else { $result .= "
" . $passed_word." ".$minutes_passed." ".$minutes_word . "
\n"; } } return $result; } ############# # print_all_txt # # Вывести журнал в текстовом формате # # In: $_[0] output_filename # Out: sub print_command_lines_txt { my $output_filename=$_[0]; my $note_number=0; my $result = q(); my $this_day_resut = q(); my $cl; my $last_tty=""; my $last_session=""; my $last_day=q(); my $last_wday=q(); my $in_range=0; my $current_command=0; my $cursor_position = 0; if ($Config{filter}) { # Инициализация фильтра for (split /&/,$Config{filter}) { my ($var, $val) = split /::/; $filter{$var} = $val || ""; } } COMMAND_LINE: for my $k (@Command_Lines_Index) { my $cl=$Command_Lines[$Command_Lines_Index[$current_command++]]; next unless $cl; # Пропускаем строки, которые противоречат фильтру # Если у нас недостаточно информации о том, подходит строка под фильтр или нет, # мы её выводим for my $filter_key (keys %filter) { next COMMAND_LINE if defined($cl->{local_session_id}) && defined($Sessions{$cl->{local_session_id}}->{$filter_key}) && $Sessions{$cl->{local_session_id}}->{$filter_key} ne $filter{$filter_key}; } # Пропускаем строки, выходящие за границу "signature", # при условии, что границы указаны # Пропускаем неправильные/прерванные/другие команды if ($Config{"from"} && $cl->{"cline"} =~ /$Config{"signature"}\s*$Config{"from"}/) { $in_range=1; next; } if ($Config{"to"} && $cl->{"cline"} =~ /$Config{"signature"}\s*$Config{"to"}/) { $in_range=0; next; } next if ($Config{"from"} && $Config{"to"} && !$in_range) || ($Config{"skip_empty"} =~ /^y/i && $cl->{"cline"} =~ /^\s*$/ ) || ($Config{"skip_wrong"} =~ /^y/i && $cl->{"err"} != 0) || ($Config{"skip_interrupted"} =~ /^y/i && $cl->{"err"} == 130); # ## ## Начинается собственно вывод ## # ### Сначала обрабатываем границы разделов ### Если тип команды "note", это граница if ($cl->{class} eq "note") { $this_day_result .= " === ".$cl->{note_title}." === \n" if $cl->{note_title}; $this_day_result .= $cl->{note}."\n"; next; } my ($sec,$min,$hour,$day,$mon,$year,$wday,$yday,$isdst) = localtime($cl->{time}); # Добавляем спереди 0 для удобочитаемости $min = "0".$min if $min =~ /^.$/; $hour = "0".$hour if $hour =~ /^.$/; $sec = "0".$sec if $sec =~ /^.$/; $class=$cl->{"class"}; # DAY CHANGE if ( $last_day ne $day) { if ($last_day) { $result .= "== ".$Day_Name[$last_wday]." == \n"; $result .= $this_day_result; } $last_day = $day; $last_wday = $wday; $this_day_result = q(); } # CONSOLE CHANGE if ($cl->{"tty"} && $last_tty ne $cl->{"tty"} && 0) { my $tty = $cl->{"tty"}; $this_day_result .= " #l3: ------- другая консоль ----\n"; $last_tty=$cl->{"tty"}; } # Session change if ( $last_session ne $cl->{"local_session_id"}) { $this_day_result .= "# ------------------------------------------------------------" . " l3: local_session_id=".$cl->{"local_session_id"} . " ---------------------------------- \n"; $last_session=$cl->{"local_session_id"}; } # TIME my @nl_counter = split (/\n/, $result); $cursor_position=length($result) - @nl_counter; if ($Config{"show_time"} =~ /^y/i) { $this_day_result .= "$hour:$min:$sec" } # COMMAND $this_day_result .= " ".$cl->{"prompt"}.$cl->{"cline"}."\n"; if ($cl->{"err"}) { $this_day_result .= " #l3: err=".$cl->{'err'}."\n"; } # OUTPUT my $last_command = $cl->{"last_command"}; if (!( $Config{"suppress_editors"} =~ /^y/i && grep ($_ eq $last_command, @{$Config{"editors"}}) || $Config{"suppress_pagers"} =~ /^y/i && grep ($_ eq $last_command, @{$Config{"pagers"}}) || $Config{"suppress_terminal"}=~ /^y/i && grep ($_ eq $last_command, @{$Config{"terminal"}}) )) { my $output = $cl->{short_output}; if ($output) { $output =~ s/^/ |/mg; } $this_day_result .= $output; } # DIFF if ( $Config{"show_diffs"} =~ /^y/i && $cl->{"diff"}) { my $diff = $cl->{"diff"}; $diff =~ s/^/ |/mg; $this_day_result .= $diff; }; # SHOT if ($Config{"show_screenshots"} =~ /^y/i && $cl->{"screenshot"}) { $this_day_result .= " #l3: screenshot=".$cl->{'screenshot'}."\n"; } #NOTES if ( $Config{"show_notes"} =~ /^y/i && $cl->{"note"}) { my $note=$cl->{"note"}; $note =~ s/\n/\n#^/msg; $this_day_result .= "#^ == ".$cl->{note_title}." ==\n" if $cl->{note_title}; $this_day_result .= "#^ ".$note."\n"; } } last: { $result .= "== ".$Day_Name[$last_wday]." == \n"; $result .= $this_day_result; } return $result; } ############# # print_edit_all_html # # Вывести страницу с текстовым представлением журнала для редактирования # # In: $_[0] output_filename # Out: sub print_edit_all_html { my $output_filename= shift; my $result; my $cursor_position = 0; $result = print_command_lines_txt; my $title = ">Журнал лабораторных работ. Правка"; $result = "" ."" ."" ."" ."$title" ."" ."" ."" ."

Журнал лабораторных работ. Правка

" ."
" ."" ."
" ."
" ."

Внимательно правим, потом сохраняем

" ."

Строки, начинающиеся символами #l3: можно трогать, только если точно знаешь, что делаешь

" ."" .""; if ($output_filename eq "-") { print $result; } else { open(OUT, ">", $output_filename) or die "Can't open $output_filename for writing\n"; binmode ":utf8"; print OUT "$result"; close(OUT); } } ############# # print_all_txt # # Вывести страницу с текстовым представлением журнала для редактирования # # In: $_[0] output_filename # Out: sub print_all_txt { my $result; $result = print_command_lines_txt; $result =~ s/>/>/g; $result =~ s/</:utf8", $output_filename) or die "Can't open $output_filename for writing\n"; print OUT "$result"; close(OUT); } } ############# # print_all_html # # # # In: $_[0] output_filename # Out: sub print_all_html { my $output_filename=$_[0]; my $result; my ($command_lines,$toc) = print_command_lines_html; my $files_section = print_files_html; $result = $debug_output; $result .= print_header_html($toc); # $result.= join "
", keys %Sessions; # for my $sess (keys %Sessions) { # $result .= join " ", keys (%{$Sessions{$sess}}); # $result .= "
"; # } $result.= "

Журнал

" . $command_lines; $result.= "

Файлы

" . $files_section if $files_section; $result.= "

Статистика

" . print_stat_html; $result.= "

Справка

" . $Html_Help . "
"; $result.= "

О программе

". $Html_About. "
"; $result.= print_footer_html; if ($output_filename eq "-") { binmode STDOUT, ":utf8"; print $result; } else { open(OUT, ">:utf8", $output_filename) or die "Can't open $output_filename for writing\n"; print OUT $result; close(OUT); } } ############# # print_header_html # # # # In: $_[0] Содержание # Out: Распечатанный заголовок sub print_header_html { my $toc = $_[0]; my $course_name = $Config{"course-name"}; my $course_code = $Config{"course-code"}; my $course_date = $Config{"course-date"}; my $course_center = $Config{"course-center"}; my $course_trainer = $Config{"course-trainer"}; my $course_student = $Config{"course-student"}; my $title = "Журнал лабораторных работ"; $title .= " -- ".$course_student if $course_student; if ($course_date) { $title .= " -- ".$course_date; $title .= $course_code ? "/".$course_code : ""; } else { $title .= " -- ".$course_code if $course_code; } # Управляющая форма my $control_form .= "
" . "Видимые элементы" . "_ x" . "
\n"; for my $element (sort keys %Elements_Visibility) { my ($skip, @e) = split /\s+/, $element; my $showhide = join "", map { "ShowHide('$_');" } @e ; $control_form .= "
". $Elements_Visibility{$element}. "
"; } $control_form .= "
\n" . "
\n"; # Управляющая форма отключена # Она слишком сильно мешает, нужно что-то переделать $control_form = ""; my $tigra_hints_array=tigra_hints_generate; my $result; $result = < $title

Журнал лабораторных работ

HEADER if ( $course_student || $course_trainer || $course_name || $course_code || $course_date || $course_center) { $result .= "

"; $result .= "Выполнил $course_student
" if $course_student; $result .= "Проверил $course_trainer
" if $course_trainer; $result .= "Курс " if $course_name || $course_code || $course_date; $result .= "$course_name " if $course_name; $result .= "($course_code)" if $course_code; $result .= ", $course_date
" if $course_date; $result .= "Учебный центр $course_center
" if $course_center; $result .= "Фильтр ".join(" ", map("$filter{$_}=$_", keys %filter))."
" if %filter; $result .= "

"; } $result .= <
Содержание
$control_form HEADER return $result; } ############# # print_footer_html # # # # # sub print_footer_html { return "\n\n"; } ############# # print_stat_html # # # # In: # Out: sub print_stat_html { %StatNames = ( FirstCommand => "Время первой команды журнала", LastCommand => "Время последней команды журнала", TotalCommands => "Количество командных строк в журнале", ErrorsPercentage => "Процент команд с ненулевым кодом завершения, %", MistypesPercentage => "Процент синтаксически неверно набранных команд, %", TotalTime => "Суммарное время работы с терминалом *, час", CommandsPerTime => "Количество командных строк в единицу времени, команда/мин", CommandsFrequency => "Частота использования команд", RareCommands => "Частота использования этих команд < 0.5%", ); @StatOrder = ( FirstCommand, LastCommand, TotalCommands, ErrorsPercentage, MistypesPercentage, TotalTime, CommandsPerTime, CommandsFrequency, RareCommands, ); # Подготовка статистики к выводу # Некоторые значения пересчитываются! # Дальше их лучше уже не использовать!!! my %CommandsFrequency = %frequency_of_command; $Stat{TotalTime} ||= 0; my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($Stat{FirstCommand} || 0); $Stat{FirstCommand} = sprintf "%02i:%02i:%02i %04i-%2i-%2i", $hour, $min, $sec, $year+1900, $mon+1, $mday; ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($Stat{LastCommand} || 0); $Stat{LastCommand} = sprintf "%02i:%02i:%02i %04i-%2i-%2i", $hour, $min, $sec, $year+1900, $mon+1, $mday; if ($Stat{TotalCommands}) { $Stat{ErrorsPercentage} = sprintf "%5.2f", $Stat{ErrorCommands}*100/$Stat{TotalCommands}; $Stat{MistypesPercentage} = sprintf "%5.2f", $Stat{MistypedCommands}*100/$Stat{TotalCommands}; } $Stat{CommandsPerTime} = sprintf "%5.2f", $Stat{TotalCommands}*60/$Stat{TotalTime} if $Stat{TotalTime}; $Stat{TotalTime} = sprintf "%5.2f", $Stat{TotalTime}/60/60; my $total_commands=0; for $command (keys %CommandsFrequency){ $total_commands += $CommandsFrequency{$command}; } if ($total_commands) { for $command (reverse sort {$CommandsFrequency{$a} <=> $CommandsFrequency{$b}} keys %CommandsFrequency){ my $command_html; my $percentage = sprintf "%5.2f",$CommandsFrequency{$command}*100/$total_commands; if ($percentage < 0.5) { my $hint = make_comment($command); $command_html = "$command"; $command_html = "$command_html" if $hint; $command_html = "$command_html" if not $hint; my $command_html = "$command_html"; $Stat{RareCommands} .= $command_html."".$CommandsFrequency{$command}." , "; } else { my $hint = make_comment($command); $command_html = "$command"; $command_html = "$command_html" if $hint; $command_html = "$command_html" if not $hint; my $command_html = "$command_html"; $percentage = sprintf "%5.2f",$percentage; $Stat{CommandsFrequency} .= "".$command_html."".$CommandsFrequency{$command}."". "|".("="x int($CommandsFrequency{$command}*100/$total_commands))."| $percentage%"; } } $Stat{CommandsFrequency} = "".$Stat{CommandsFrequency}."
"; $Stat{RareCommands} =~ s/, $// if $Stat{RareCommands}; } my $result = q(); for my $stat (@StatOrder) { next unless $Stat{"$stat"}; $result .= "".$StatNames{"$stat"}."".$Stat{"$stat"}."" } $result = "$result
" . "____
*) Интервалы неактивности длительностью " . ($Config{stat_inactivity_interval}/60) . " минут и более не учитываются

"; return $result; } sub collapse_list($) { my $res = ""; for my $elem (@{$_[0]}) { if (ref $elem eq "ARRAY") { $res .= "
    ".collapse_list($elem)."
"; } else { $res .= "
  • ".$elem."
  • "; } } return $res; } sub print_files_html { my $result = qq(); my @toc; for my $file (sort keys %Files) { my $div_id = "file:$file"; $div_id =~ s@/@_@g; push @toc, "$file"; $result .= "
    ".$file."
    \n" . "" . "
    ".$Files{$file}->{content}."
    "; } if ($result) { return "
    ".collapse_list(\@toc)."
    ".$result; } else { return ""; } } sub init_variables { $Html_Help = <
  • В журнал автоматически попадают все команды, данные в любом терминале системы.

  • Для того чтобы убедиться, что журнал на текущем терминале ведётся, и команды записываются, дайте команду w. В поле WHAT, соответствующем текущему терминалу, должна быть указана программа script.

  • Команды, при наборе которых были допущены синтаксические ошибки, выводятся перечёркнутым текстом:
    \$ l s-l
    bash: l: command not found
    

  • Если код завершения команды равен нулю, команда была выполнена без ошибок. Команды, код завершения которых отличен от нуля, выделяются цветом.
    \$ test 5 -lt 4
    Обратите внимание на то, что код завершения команды может быть отличен от нуля не только в тех случаях, когда команда была выполнена с ошибкой. Многие команды используют код завершения, например, для того чтобы показать результаты проверки

  • Команды, ход выполнения которых был прерван пользователем, выделяются цветом.
    \$ find / -name abc
    find: /home/devi-orig/.gnome2: Keine Berechtigung
    find: /home/devi-orig/.gnome2_private: Keine Berechtigung
    find: /home/devi-orig/.nautilus/metafiles: Keine Berechtigung
    find: /home/devi-orig/.metacity: Keine Berechtigung
    find: /home/devi-orig/.inkscape: Keine Berechtigung
    ^C
    

  • Команды, выполненные с привилегиями суперпользователя, выделяются слева красной чертой.
    # id
    uid=0(root) gid=0(root) Gruppen=0(root)
    

  • Изменения, внесённые в текстовый файл с помощью редактора, запоминаются и показываются в журнале в формате ed. Строки, начинающиеся символом "<", удалены, а строки, начинающиеся символом ">" -- добавлены.
    \$ vi ~/.bashrc
    2a3,5
    >    if [ -f /usr/local/etc/bash_completion ]; then
    >         . /usr/local/etc/bash_completion
    >        fi
    

  • Для того чтобы изменить файл в соответствии с показанными в диффшоте изменениями, можно воспользоваться командой patch. Нужно скопировать изменения, запустить программу patch, указав в качестве её аргумента файл, к которому применяются изменения, и всавить скопированный текст:
    \$ patch ~/.bashrc
    В данном случае изменения применяются к файлу ~/.bashrc

  • Для того чтобы получить краткую справочную информацию о команде, нужно подвести к ней мышь. Во всплывающей подсказке появится краткое описание команды.

    Если справочная информация о команде есть, команда выделяется голубым фоном, например: vi. Если справочная информация отсутствует, команда выделяется розовым фоном, например: notepad.exe. Справочная информация может отсутствовать в том случае, если (1) команда введена неверно; (2) если распознавание команды LiLaLo выполнено неверно; (3) если информация о команде неизвестна LiLaLo. Последнее возможно для редких команд.

  • Большие, в особенности многострочные, всплывающие подсказки лучше всего показываются браузерами KDE Konqueror, Apple Safari и Microsoft Internet Explorer. В браузерах Mozilla и Firefox они отображаются не полностью, а вместо перевода строки выводится специальный символ.

  • Время ввода команды, показанное в журнале, соответствует времени начала ввода командной строки, которое равно тому моменту, когда на терминале появилось приглашение интерпретатора

  • Имя терминала, на котором была введена команда, показано в специальном блоке. Этот блок показывается только в том случае, если терминал текущей команды отличается от терминала предыдущей.

  • Вывод не интересующих вас в настоящий момент элементов журнала, таких как время, имя терминала и других, можно отключить. Для этого нужно воспользоваться формой управления журналом вверху страницы.

  • Небольшие комментарии к командам можно вставлять прямо из командной строки. Комментарий вводится прямо в командную строку, после символов #^ или #v. Символы ^ и v показывают направление выбора команды, к которой относится комментарий: ^ - к предыдущей, v - к следующей. Например, если в командной строке было введено:

    \$ whoami
    
    user
    
    \$ #^ Интересно, кто я?
    
    в журнале это будет выглядеть так:
    \$ whoami
    
    user
    
    Интересно, кто я?

  • Если комментарий содержит несколько строк, его можно вставить в журнал следующим образом:

    \$ whoami
    
    user
    
    \$ cat > /dev/null #^ Интересно, кто я?
    
    Программа whoami выводит имя пользователя, под которым 
    мы зарегистрировались в системе.
    -
    Она не может ответить на вопрос о нашем назначении 
    в этом мире.
    
    В журнале это будет выглядеть так:
    \$ whoami
    user
    
    Интересно, кто я?
    Программа whoami выводит имя пользователя, под которым
    мы зарегистрировались в системе.

    Она не может ответить на вопрос о нашем назначении
    в этом мире.
    Для разделения нескольких абзацев между собой используйте символ "-", один в строке.

  • Комментарии, не относящиеся непосредственно ни к какой из команд, добавляются точно таким же способом, только вместо симолов #^ или #v нужно использовать символы #=

  • Содержимое файла может быть показано в журнале. Для этого его нужно вывести с помощью программы cat. Если вывод команды отметить симоволами #!, содержимое файла будет показано в журнале в специально отведённой для этого секции.
  • Для того чтобы вставить скриншот интересующего вас окна в журнал, нужно воспользоваться командой l3shot. После того как команда вызвана, нужно с помощью мыши выбрать окно, которое должно быть в журнале.
  • Команды в журнале расположены в хронологическом порядке. Если две команды давались одна за другой, но на разных терминалах, в журнале они будут рядом, даже если они не имеют друг к другу никакого отношения.
    1
        2
    3   
        4
    
    Группы команд, выполненных на разных терминалах, разделяются специальной линией. Под этой линией в правом углу показано имя терминала, на котором выполнялись команды. Для того чтобы посмотреть команды только одного сенса, нужно щёкнуть по этому названию.
  • HELP $Html_About = < LiLaLo (L3) расшифровывается как Live Lab Log.
    Программа разработана для повышения эффективности обучения Unix/Linux-системам.
    (c) Игорь Чубин, 2004-2008

    ABOUT $Html_About.='$Id$

    '; $Html_JavaScript = <0) subelems[j].style.display = "none"; else subelems[j].style.display = ""; } } } } JS $SetCursorPosition_JS = < { "query" => "http://www.google.com/search?q=" , "icon" => "$Config{frontend_google_ico}" }, "freebsd" => { "query" => "http://www.freebsd.org/cgi/man.cgi?query=", "icon" => "$Config{frontend_freebsd_ico}" }, "linux" => { "query" => "http://man.he.net/?topic=", "icon" => "$Config{frontend_linux_ico}"}, "opennet" => { "query" => "http://www.opennet.ru/search.shtml?words=", "icon" => "$Config{frontend_opennet_ico}"}, "local" => { "query" => "http://www.freebsd.org/cgi/man.cgi?query=", "icon" => "$Config{frontend_local_ico}" }, ); %Elements_Visibility = ( "0 new_commands_table" => "новые команды", "1 diff" => "редактор", "2 time" => "время", "3 ttychange" => "терминал", "4 wrong_output wrong_cline wrong_root_output wrong_root_cline" => "команды с ненулевым кодом завершения", "5 mistyped_output mistyped_cline mistyped_root_output mistyped_root_cline" => "неверно набранные команды", "6 interrupted_output interrupted_cline interrupted_root_output interrupted_root_cline" => "прерванные команды", "7 tab_completion_output tab_completion_cline" => "продолжение с помощью tab" ); @Day_Name = qw/ Воскресенье Понедельник Вторник Среда Четверг Пятница Суббота /; @Month_Name = qw/ Январь Февраль Март Апрель Май Июнь Июль Август Сентябрь Октябрь Ноябрь Декабрь /; @Of_Month_Name = qw/ Января Февраля Марта Апреля Мая Июня Июля Августа Сентября Октября Ноября Декабря /; } # Временно удалённый код # Возможно, он не понадобится уже никогда sub search_by { my $sm = shift; my $topic = shift; $topic =~ s/ /+/; return ""; } ######################################################################################## # # mywi # # # # # # # sub mywi_init { our $MyWiFile = "/home/igor/mywi/mywi.txt"; our $MyWiLog = "/home/igor/mywi/mywi.log"; our $section=""; our @MywiTXT; # Массив текстовых записей mywi our %MywiHASH; # Хэш массивов записей our %Query; load_mywitxt($MyWiFile, \@MywiTXT, \%MywiHASH); } sub mywi_process_query($) # # Сделать подсказку по заданному запросу # $_[0] - тема для подсказки # # Возвращает: # строку-подсказку # { my $query = shift; parse_query($query, \%Query); $result = search_in_txt(\%Query, \@MywiTXT, \%MywiHASH); if (!$result) { #add_to_log(\%Query, $MyWiLog); return "$query nothing appropriate. Logged. ".join (";",%Query); } return $result; } #################################################################################### # private section #################################################################################### sub load_mywitxt # # Загрузить файл с записями Mywi_TXT # в массив # $_[0] - указатель на массив для загрузки # $_[1] - имя файла для загрузки # { my $MyWiFile = $_[0]; my $MywiTXT = $_[1]; my $MywiHASH = $_[2]; open (MW, "$MyWiFile") or die "Can't open $MyWiFile for reading"; binmode MW, ":utf8"; @{$MywiTXT} = ; close (MWF); for my $mywi_line (@{$MywiTXT}) { my $topic = $mywi_line; $topic =~ s@\s*\(.*\n@@; push @{$$MywiHASH{"$topic"}}, $mywi_line; # $MywiHASH{"$topic"} .= $mywi_line; } } sub parse_query # # Строка запроса: # [format:]topic[(section)] # Элементы format и topic являются не обязательными # # $_[0] - строка запроса # $_[1] - ссылка на хэш запроса # { my $query_string = shift; my $query_hash = shift; %{$query_hash} = ( "format" => "txt", "section" => "", "topic" => "", ); if ($query_string =~ s/^([^:]*)://) { $query_hash->{"format"} = $1 || "txt"; } if ($query_string =~ s/\(([^(]*)\)$//) { $query_hash->{"section"} = $1 || ""; } $query_hash->{"topic"} = $query_string; } sub search_in_txt # # Выполнить поиск в текстовой базе # по известному запросу # $_[0] -- ссылка на хэш запроса # $_[1] -- ссылка на массив текстовых записей # $_[2] -- ссылка на хэш массивов текстовых записей # Результат: # найденная текстовая запись в заданном формате # { my %Query = %{$_[0]}; my %MywiHASH = %{$_[2]}; my $topic = $Query{"topic"}; my $section = $Query{"section"}; my $result = ""; return join("\n",@{$MywiHASH{"$topic"}})."\n"; for my $l (@{$$_[2]{$topic}}) { # for my $l (@{$_[1]}) { my $line = $l; if ( ($section and $line =~ /^\s*\Q$topic\E\s*\($section*\)\s*-/ ) or (not $section and $line =~ /^\s*\Q$topic\E\s*(\([^)]*\)?)\s*-/) ) { $line =~ s/^.* -//mg if ($Config{"short"}); $result .= "$line"; } } return $result; } sub add_to_log($$) # # Если в базе отсутствует информация по данной теме, # сделать предположение доступным способом # и добавить его в базу # или просто сделать отметку о необходимости # расширения базы # # Добавить запись в журнал # $_[0] - запись (ссылка на хэш) # $_[1] - имя файла-журнала # { my $query = $_[0]; my $MyWiLog = $_[1]; open (MWF, ">>:utf8", $MyWiLog) or die "Can't open $MyWiLog for writing"; my $my_guess = mywi_guess($query); print MWF "$my_guess\n"; close(MWF); } sub mywi_guess($) # Сформировать исходную строку для журнала по заданному запросу # Если секция принадлежит 0..9, в качестве основы для результирующего текста использовать whatis # $_[0] - запись (ссылка на хэш) # # Возвращает: # строку-предположение { my %query = %{$_[0]}; my $topic = $query{"topic"}; my $section = $query{"section"}; my $result = "$topic($section)"; if (!$section or $section =~ /^[1-9]$/) { # Запрос из категории 1-9 # Об этом может знать whatis $result = `LANG=C whatis -- "$topic"`; if ($result =~ /nothing appropriate/i) { $result = $topic; $result .= "($section)" if $section; } else { 1 while ($result =~ s/(\s+)-(\s+)/$1+$2/sg); $result =~ s/\s+\(/(/; chomp $result; } } return $result; }