#!/usr/bin/perl -w

use POSIX qw(strftime);
use lib '.';
use l3config;
use utf8;

our @Command_Lines;
our @Command_Lines_Index;
our %Commands_Description;
our %Args_Description;
our %Sessions;

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 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_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 '<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].
'</div></div></div></div></div></div></div></div>';
}

sub tigra_hints_generate
{
    my $tigra_hints_items="";
    for my $hint_id (keys %tigra_hints) {
        $tigra_hints{$hint_id} =~ s@\n@<br/>@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 <<TIGRA;

var HINTS_CFG = {
	'top'        : 5, // a vertical offset of a hint from mouse pointer
	'left'       : 5, // a horizontal offset of a hint from mouse pointer
	'css'        : 'hintsClass', // a style class name for all hints, TD object
	'show_delay' : 500, // a delay between object mouseover and hint appearing
	'hide_delay' : 2000, // a delay between hint appearing and hint hiding
	'wise'       : true,
	'follow'     : true,
	'z-index'    : 0 // a z-index for all hint layers
},

HINTS_CFG_NEW = {
    'wise'       : true, // don't go off screen, don't overlap the object in the document
    'margin'     : 10, // minimum allowed distance between the hint and the window edge (negative values accepted)
    'gap'        : 20, // minimum allowed distance between the hint and the origin (negative values accepted)
    '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)
    'css'        : 'hintsClass', // a style class name for all hints, applied to DIV element (see style section in the header of the document)
    'show_delay' : 0, // a delay between initiating event (mouseover for example) and hint appearing
    'hide_delay' : 200, // a delay between closing event (mouseout for example) and hint disappearing
    'follow'     : true, // hint follows the mouse as it moves
    'z-index'    : 100, // a z-index for all hint layers
    'IEfix'      : false, // fix IE problem with windowed controls visible through hints (activate if select boxes are visible through the hints)
    'IEtrans'    : ['blendTrans(DURATION=.3)', null], // [show transition, hide transition] - nice transition effects, only work in IE5+
    'opacity'    : 90 // opacity of the hint in %%
},

HINTS_ITEMS = {
    $tigra_hints_items
};
var myHint = new THints (HINTS_CFG, HINTS_ITEMS);


function mywrap (s_) {
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_+
'</div></div></div></div></div></div></div></div>';

}
TIGRA
$a=<<TIGRA;
TIGRA
}


sub count_frequency_of_commands
{
    my $cline = $_[0];
    my @commands = keys %{extract_from_cline("commands", $cline)};
    for my $command (@commands) {
        $frequency_of_command{$command}++;
    }
}

sub make_comment
{
    my $cline = $_[0];
    #my $files = $_[1];

    my @comments;
    my @commands = keys %{extract_from_cline("commands", $cline)};
    my @args = keys %{extract_from_cline("args", $cline)};
    return if (!@commands && !@args);
    #return "commands=".join(" ",@commands)."; files=".join(" ",@files);

    # Commands
    for my $command (@commands) {
        $command =~ s/'//g;
        #$frequency_of_command{$command}++;
        if (!$Commands_Description{$command}) {
            $mywi_cache_for{$command} ||= mywi_process_query($command) || "";
            my $mywi = join ("\n", grep(/\([18]|sh|script\)/, split(/\n/, $mywi_cache_for{$command})));
            $mywi =~ s/\s+/ /;
            if ($mywi !~ /^\s*$/) {
                $Commands_Description{$command} = $mywi;
            }
            else {
                next;
            }
        }

        push @comments, $Commands_Description{$command};
    }
    return join("&#10;\n", @comments);
    
    # Files
    for my $arg (@args) {
        $arg =~ s/'//g;
        if (!$Args_Description{$arg}) {
            my $mywi;
            $mywi = mywi_client ($arg);
            $mywi = join ("\n", grep(/\([5]\)/, split(/\n/, $mywi)));
            $mywi =~ s/\s+/ /;
            if ($mywi !~ /^\s*$/) {
                $Args_Description{$arg} = $mywi;
            }
            else {
                next;
            }
        }

        push @comments, $Args_Description{$arg};
    }

}

=cut
Процедура load_command_lines_from_xml выполняет загрузку разобранного lab-скрипта
из XML-документа в переменную @Command_Lines

# In:       $datafile           имя файла
# Out:      @CommandLines       загруженные командные строки

Предупреждение!
Процедура не в состоянии обрабатывать XML-документ любой структуры.
В действительности файл cache из которого загружаются данные 
просто напоминает XML с виду.
=cut
sub load_command_lines_from_xml
{
    my $datafile = $_[0];

    open (CLASS, $datafile)
        or die "Can't open file with xml lablog ",$datafile,"\n";
    local $/;
    binmode CLASS, ":utf8";
    $data = <CLASS>;
    close(CLASS);

    for $command ($data =~ m@<command>(.*?)</command>@sg) {
        my %cl;
        while ($command =~ m@<([^>]*?)>(.*?)</\1>@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 = <CLASS>;
    close(CLASS);

    my $i=0;
    for my $session ($data =~ m@<session>(.*?)</session>@msg) {
        my %session_hash;
        while ($session =~ m@<([^>]*?)>(.*?)</\1>@sg) {
            $session_hash{$1} = $2;
        }
        $Sessions{$session_hash{local_session_id}} = \%session_hash;
    }
}


# 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;

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];

        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}="";

# Выводим <head_lines> верхних строк
# и <tail_lines> нижних строк,
# если эти параметры существуют
        my $output="";

        if ($$cl->{"last_command"} eq "cat" && !$$cl->{"err"} && !($$cl->{"cline"} =~ /</)) {
            my $filename = $$cl->{"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;

#Обработка пометок
#  Если несколько пометок (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 ("<p>$_</p>", split (/-\n/, $note_html)));
                $note_html =~ s@(http:[a-zA-Z.0-9/?\_%-]*)@<a href='$1'>$1</a>@g;
                $note_html =~ s@(www\.[a-zA-Z.0-9/?\_%-]*)@<a href='$1'>$1</a>@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;

        next if $current_command < $Config{"start_from_command"};
        last if $current_command > $Config{"start_from_command"} + $Config{"commands_to_show_at_a_go"};


# Пропускаем команды, с одинаковым временем
# Это не совсем правильно.
# Возможно, что это команды, набираемые с помощью <completion>
# или запомненные с помощью <ctrl-c>

        next if $Stat{LastCommand} == $cl->{time};

# Пропускаем строки, которые противоречат фильтру
# Если у нас недостаточно информации о том, подходит строка под  фильтр или нет, 
# мы её выводим

        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 .= "Время идёт вспять<br/>";
        };
        $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 .= "<tr><td colspan='6'>"
                             .  "<h4 id='note$note_number'>".$cl->{note_title}."</h4>" if $cl->{note_title}
                             .  "".$cl->{note_html}."<p/><p/></td></tr>";

            if ($cl->{note_title}) {
                push @{$toc[@toc]},"<a href='#note$note_number'>".$cl->{note_title}."</a>";
                $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 .= "<h3 id='day_on_sec_$prev_unix_time'>".$Day_Name[$last_wday]." ($human_readable_time)</h3>";
                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, "<a href='#day_on_sec_$first_command_of_the_day_unix_time'>".$Day_Name[$wday]." ($human_readable_time)</a>\n";


            $last_day=$day;
            $last_wday=$wday;
            $this_day_result = q();
        }
        else {
            $this_day_result .= minutes_passed($seconds_since_last_command);
        }

        $this_day_result .= "<div class='command' id='command:".$cl->{"id"}."' >\n";

# CONSOLE CHANGE
        if ($cl->{"tty"} && $last_tty ne $cl->{"tty"} && 0) {
            my $tty = $cl->{"tty"};
            $this_day_result .= "<div class='ttychange'>"
                                . $tty
                                ."</div>";
            $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 .= "<div class='ttychange'><a href='?local_session_id=".$cl->{"local_session_id"}."'>"
                                . $Sessions{$cl->{"local_session_id"}}->{"tty"}
                                ."</a></div>";
            }
            $last_session=$cl->{"local_session_id"};
        }

# TIME
        if ($Config{"show_time"} =~ /^y/i) {
            $this_day_result .= "<div class='time'>$hour:$min:$sec</div>" 
        }

# COMMAND
        my $cline;
        $prompt_hint = join ("&#10;", map("$_=$cl->{$_}", grep (!/^(output|diff)$/, sort(keys(%{$cl})))));
        $cline = "<span title='$prompt_hint'>".$cl->{"prompt"}."</span>"
                ."<span onmouseover=\"myHint.show('".$cl->{time}."')\" onmouseout=\"myHint.hide()\">".$cl->{"cline"}."</span>";
        $cline =~ s/\n//;

        if ($cl->{"hint"}) {
#            $cline = "<span title='$cl->{hint}' class='with_hint'>$cline</span>" ;
            $cline = "<span class='with_hint'>$cline</span>" ;
        } 
        else {
            $cline = "<span class='without_hint'>$cline</span>";
        }

        $this_day_result .= "<DIV class='fixed_div'><table cellpadding='0' cellspacing='0'><tr><td>\n<div class='cblock_$cl->{class}'>\n";
        $this_day_result .= "<div class='cline'>" . $cline ;      #cline
        $this_day_result .= "<span title='Код завершения ".$cl->{"err"}."'>\n"
                         .  "<img src='".$Config{frontend_ico_path}."/error.png'/>\n"
                         .  "</span>\n" if $cl->{"err"};
        $this_day_result .= "</div>\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 .= "<pre class='output'>\n" . $cl->{short_output} . "</pre>\n";
        }

# DIFF
        $this_day_result .= "<pre class='diff'>".$cl->{"diff"}."</pre>"
            if ( $Config{"show_diffs"} =~ /^y/i && $cl->{"diff"});
# SHOT
        $this_day_result .= "<img src='"
                .$Config{l3shot_path}
                .$cl->{"screenshot"}
                ."' alt ='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/<br\/>\n/msg;
            if (not $note =~ s@(http:[a-zA-Z.0-9/_?%-]*)@<a href='$1'>$1</a>@g) {
              $note =~ s@(www\.[a-zA-Z.0-9/_?%-]*)@<a href='$1'>$1</a>@g;
            };
            $this_day_result .= "<div class='note'>";
            $this_day_result .= "<div class='note_title'>".$cl->{note_title}."</div>" if $cl->{note_title};
            $this_day_result .= "<div class='note_text'>".$note."</div>";
            $this_day_result .= "</div>\n";
        }

        # Вывод очередной команды окончен
        $this_day_result .= "</div>\n";                     # cblock
        $this_day_result .= "</td></tr></table></DIV>\n"
                         .  "</div>\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 .= "<h3 id='day_on_sec_$prev_unix_time'>".$Day_Name[$last_wday]." ($human_readable_time)</h3>";

        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 .= "<tr><td valign='top'>$command</td><td>$hint</td></tr>";
        }
    }
    if ($new_commands_section) {
        $result .= "<table class='new_commands_table' width='700' cellspacing='0' cellpadding='0'>"
                .  "<tr class='new_commands_caption'>"
                .  "<td colspan='2' align='right'>$table_caption</td>"
                .  "</tr>"
                .  "<tr class='new_commands_header'>"
                .  "<td width=100>Команда</td><td width=600>Описание</td>"
                .  "</tr>"
                .  $new_commands_section 
                .  "</table>"
    }
    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 .= "<div class='much_time_passed'>"
                    .  $passed_word." &gt;".$hours_passed." ".$hours_word
                    .  "</div>\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 .= "<div class='time_passed'>"
                        .  $passed_word." ".$minutes_passed." ".$minutes_word
                        .  "</div>\n";
            }
            else {
                $result .= "<div class='much_time_passed'>"
                        .  $passed_word." ".$minutes_passed." ".$minutes_word
                        .  "</div>\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 = 
               "<html>"
                ."<head>"
                ."<meta content='text/html; charset=utf-8' http-equiv='Content-Type' />"
                ."<link rel='stylesheet' href='$Config{frontend_css}' type='text/css'/>"
                ."<title>$title</title>"
                ."</head>"
              ."<script>"
              .$SetCursorPosition_JS
              ."</script>"
              ."<body onLoad='setCursorPosition(document.all.mytextarea, $cursor_position, $cursor_position+10)'>"
              ."<h1>Журнал лабораторных работ. Правка</h1>"
              ."<form>"
              ."<textarea rows='30' cols='100' wrap='off' id='mytextarea'>$result</textarea>"
              ."<br/><input type='submit' value='Сохранить' label='label'/>"
              ."</form>"
              ."<p>Внимательно правим, потом сохраняем</p>"
              ."<p>Строки, начинающиеся символами #l3: можно трогать, только если точно знаешь, что делаешь</p>"
              ."</body>"
              ."</html>";

    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/&gt;/>/g;
    $result =~ s/&lt;/</g;
    $result =~ s/&amp;/&/g;

    if ($output_filename eq "-") {
        print $result;
    }
    else {
        open(OUT, ">: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 " <br/>", keys %Sessions;
#    for my $sess (keys %Sessions) {
#            $result .= join " ", keys (%{$Sessions{$sess}});
#            $result .= "<br/>";
#    }

    $result.= "<h2 id='log'>Журнал</h2>"       . $command_lines;
    $result.= "<h2 id='files'>Файлы</h2>"      . $files_section if $files_section;
    $result.= "<h2 id='stat'>Статистика</h2>"  . print_stat_html;
    $result.= "<h2 id='help'>Справка</h2>"     . $Html_Help . "<br/>"; 
    $result.= "<h2 id='about'>О программе</h2>". $Html_About. "<br/>"; 
    $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 .= "<div class='visibility_form' title='Выберите какие элементы должны быть показаны в журнале'>"
                     .  "<span class='header'>Видимые элементы</span>"
                     .  "<span class='window_controls'><a href='' onclick='' title='свернуть форму управления'>_</a> <a href='' onclick='' title='закрыть форму управления'>x</a></span>"
                     .  "<div><form>\n";
    for my $element (sort keys %Elements_Visibility)
    {
        my ($skip, @e) = split /\s+/, $element;
        my $showhide = join "", map { "ShowHide('$_');" } @e ;
        $control_form .= "<div><input type='checkbox' name='$e[0]' onclick=\"$showhide\" checked>".
                $Elements_Visibility{$element}.
                "</input></div>";
    }
    $control_form .= "</form>\n"
                  .  "</div>\n";


    # Управляющая форма отключена
    # Она слишком сильно мешает, нужно что-то переделать
    $control_form = "";

    my $tigra_hints_array=tigra_hints_generate;

    my $result;
    $result = <<HEADER;
    <html>
    <head>
    <meta content='text/html; charset=utf-8' http-equiv='Content-Type' />
    <link rel='stylesheet' href='$Config{frontend_css}' type='text/css'/>
    <title>$title</title>
    </head>
    <body>
    <!--<script>
    $Html_JavaScript
    </script>-->

<!-- vvv Tigra Hints vvv -->
<script language="JavaScript" src="/tigra/hints.js"></script>
<!--<script language="JavaScript" src="/tigra/hints_cfg.js"></script>-->
<script>$tigra_hints_array</script>
<style>
/* a class for all Tigra Hints boxes, TD object */
    .hintsClass
        {text-align: left; font-size:80%; font-family: Verdana, Arial, Helvetica; background-color:#ffffee; padding: 0px 0px 0px 0px;}
/* this class is used by Tigra Hints wrappers */
    .row
        {background: white;}


    .bl2 {border: 1px solid #e68200; background:url(/tigra/block/bl2.gif) 0 100% no-repeat; text-align:left}
    .bl {background:url(/tigra/block/bl2.gif) 0 100% no-repeat; text-align:left}
    .br {background:url(/tigra/block/br2.gif) 100% 100% no-repeat}
    .tl {background:url(/tigra/block/tl2.gif) 0 0 no-repeat}
    .tr {background:url(/tigra/block/tr2.gif) 100% 0 no-repeat; padding:10px}
    .tr2 {background:url(/tigra/block/tr2.gif) 100% 0 no-repeat}
    .t {background:url(/tigra/block/dot2.gif) 0 0 repeat-x}
    .b {background:url(/tigra/block/dot2.gif) 0 100% repeat-x}
    .l {background:url(/tigra/block/dot2.gif) 0 0 repeat-y}
    .r {background:url(/tigra/block/dot2.gif) 100% 0 repeat-y}


</style>
<!-- ^^^ Tigra Hints ^^^ -->

<!--
    .bl2 {border: 1px solid #e68200; background:url(/tigra/block/bl2.gif) 0 100% no-repeat; width:20em; text-align:center}
    .bl {background:url(/tigra/block/bl2.gif) 0 100% no-repeat; width:20em; text-align:center}
    .br {background:url(/tigra/block/br2.gif) 100% 100% no-repeat}
    .tl {background:url(/tigra/block/tl2.gif) 0 0 no-repeat}
    .tr {background:url(/tigra/block/tr2.gif) 100% 0 no-repeat; padding:10px}
    .tr2 {background:url(/tigra/block/tr2.gif) 100% 0 no-repeat}
    .t {background:url(/tigra/block/dot2.gif) 0 0 repeat-x; width:20em}
    .b {background:url(/tigra/block/dot2.gif) 0 100% repeat-x}
    .l {background:url(/tigra/block/dot2.gif) 0 0 repeat-y}
    .r {background:url(/tigra/block/dot2.gif) 100% 0 repeat-y}
-->


    <div class='edit_link'>
    [ <a href='?action=edit&$filter_url'>править</a> ]
    </div>
    <h1 onmouseover="myHint.show('1')" onmouseout="myHint.hide()" class='lined_header'>Журнал лабораторных работ</h1>
HEADER
    if (    $course_student 
            || $course_trainer 
            || $course_name 
            || $course_code 
            || $course_date 
            || $course_center) {
            $result .= "<p>";
            $result .= "Выполнил $course_student<br/>"  if $course_student;
            $result .= "Проверил $course_trainer <br/>" 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<br/>"            if $course_date;
            $result .= "Учебный центр $course_center <br/>" if $course_center;
            $result .= "Фильтр ".join(" ", map("$filter{$_}=$_", keys %filter))."<br/>" if %filter;
            $result .= "</p>";
    }

    $result .= <<HEADER;
    <table width='100%'>
    <tr>
    <td width='*'>

    <table border=0 id='toc' class='toc'>
    <tr>
    <td>
    <div class='toc_title'>Содержание</div>
    <ul>
        <li><a href='#log'>Журнал</a></li>
        <ul>$toc</ul>
        <li><a href='#files'>Файлы</a></li>
        <li><a href='#stat'>Статистика</a></li>
        <li><a href='#help'>Справка</a></li>
        <li><a href='#about'>О программе</a></li>
    </ul>
    </td>
    </tr>
    </table>

    </td>
    <td valign='top' width=200>$control_form</td>
    </tr>
    </table>
HEADER

    return $result;
}


#############
# print_footer_html
#
#
#
#
#

sub print_footer_html
{
    return "</body>\n</html>\n";
}




#############
# print_stat_html
#
#
#
# In:
# Out:

sub print_stat_html
{
    %StatNames = (
        FirstCommand        => "Время первой команды журнала",
        LastCommand         => "Время последней команды журнала",
        TotalCommands       => "Количество командных строк в журнале",
        ErrorsPercentage    => "Процент команд с ненулевым кодом завершения, %",
        MistypesPercentage  => "Процент синтаксически неверно набранных команд, %",
        TotalTime           => "Суммарное время работы с терминалом <sup><font size='-2'>*</font></sup>, час",
        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 = "<span title='$hint' class='with_hint'>$command_html</span>" if $hint;
                $command_html = "<span class='without_hint'>$command_html</span>" if not $hint;
                my $command_html = "<tt>$command_html</tt>";
                $Stat{RareCommands} .= $command_html."<sub><font size='-2'>".$CommandsFrequency{$command}."</font></sub> , ";
            }
            else {
                my $hint = make_comment($command);
                $command_html = "$command";
                $command_html = "<span title='$hint' class='with_hint'>$command_html</span>" if $hint;
                $command_html = "<span class='without_hint'>$command_html</span>" if not $hint;
                my $command_html = "<tt>$command_html</tt>";
                $percentage = sprintf "%5.2f",$percentage;
                $Stat{CommandsFrequency} .= "<tr><td>".$command_html."</td><td>".$CommandsFrequency{$command}."</td>".
                    "<td>|".("="x int($CommandsFrequency{$command}*100/$total_commands))."| $percentage%</td></tr>";
            }
        }
        $Stat{CommandsFrequency} = "<table>".$Stat{CommandsFrequency}."</table>";
        $Stat{RareCommands} =~ s/, $// if $Stat{RareCommands};
    }

    my $result = q();
    for my $stat (@StatOrder) {
        next unless $Stat{"$stat"};
        $result .= "<tr valign='top'><td width='300'>".$StatNames{"$stat"}."</td><td>".$Stat{"$stat"}."</td></tr>"
    }
    $result  = "<table>$result</table>"
             . "<font size='-2'>____<br/>*) Интервалы неактивности длительностью "
             .  ($Config{stat_inactivity_interval}/60)
             . " минут и более не учитываются</font></br>";

    return $result;
}


sub collapse_list($)
{
    my $res = "";
    for my $elem (@{$_[0]}) {
        if (ref $elem eq "ARRAY") {
            $res .= "<ul>".collapse_list($elem)."</ul>";
        }
        else
        {
            $res .= "<li>".$elem."</li>";
        }
    }
    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, "<a href='#$div_id'>$file</a>";
          $result .= "<div class='filename' id='$div_id'>".$file."</div>\n"
                  .  "<div class='file_navigation'><a href='#command:".$Files{$file}->{source_command_id}."'>"."&gt;"."</a></div>"
                  .  "<div class='filedata'><pre>".$Files{$file}->{content}."</pre></div>";
    }
    if ($result) {
        return "<div class='files_toc'>".collapse_list(\@toc)."</div>".$result;
    } 
    else {
        return "";
    }
}


sub init_variables
{
$Html_Help = <<HELP;
    Для того чтобы использовать LiLaLo, не нужно знать ничего особенного:
    всё происходит само собой.
    Однако, чтобы ведение и последующее использование журналов
    было как можно более эффективным, желательно иметь в виду следующее:
    <ol>
    <li><p> 
    В журнал автоматически попадают все команды, данные в любом терминале системы.
    </p></li>
    <li><p>
    Для того чтобы убедиться, что журнал на текущем терминале ведётся, 
    и команды записываются, дайте команду w.
    В поле WHAT, соответствующем текущему терминалу, 
    должна быть указана программа script.
    </p></li>
    <li><p>
    Команды, при наборе которых были допущены синтаксические ошибки, 
    выводятся перечёркнутым текстом:
<table>
<tr class='command'>
<td class='script'>
<pre class='_mistyped_cline'>
\$ l s-l</pre>
<pre class='_mistyped_output'>bash: l: command not found
</pre>
</td>
</tr>
</table>
<br/>
    </p></li>
    <li><p>
    Если код завершения команды равен нулю, 
    команда была выполнена без ошибок.
    Команды, код завершения которых отличен от нуля, выделяются цветом.
<table>
<tr class='command'>
<td class='script'>
<pre class='_wrong_cline'>
\$ test 5 -lt 4</pre>
</pre>
</td>
</tr>
</table>
    Обратите внимание на то, что код завершения команды может быть отличен от нуля
    не только в тех случаях, когда команда была выполнена с ошибкой.
    Многие команды используют код завершения, например, для того чтобы показать результаты проверки
<br/>
    </p></li>
    <li><p>
    Команды, ход выполнения которых был прерван пользователем, выделяются цветом.
<table>
<tr class='command'>
<td class='script'>
<pre class='_interrupted_cline'>
\$ find / -name abc</pre>
<pre class='interrupted_output'>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
</pre>
</td>
</tr>
</table>
<br/>
    </p></li>
    <li><p>
    Команды, выполненные с привилегиями суперпользователя,
    выделяются слева красной чертой.
<table>
<tr class='command'>
<td class='script'>
<pre class='_root_cline'>
# id</pre>
<pre class='_root_output'>
uid=0(root) gid=0(root) Gruppen=0(root)
</pre>
</td>
</tr>
</table>
    <br/>
    </p></li>
    <li><p>
    Изменения, внесённые в текстовый файл с помощью редактора, 
    запоминаются и показываются в журнале в формате ed.
    Строки, начинающиеся символом "&lt;", удалены, а строки,
    начинающиеся символом "&gt;" -- добавлены.
<table>
<tr class='command'>
<td class='script'>
<pre class='cline'>
\$ vi ~/.bashrc</pre>
<table><tr><td width='5'/><td class='diff'><pre>2a3,5
&gt;    if [ -f /usr/local/etc/bash_completion ]; then
&gt;         . /usr/local/etc/bash_completion
&gt;        fi
</pre></td></tr></table></td>
</tr>
</table>
    <br/>
    </p></li>
    <li><p>
    Для того чтобы изменить файл в соответствии с показанными в диффшоте
    изменениями, можно воспользоваться командой patch.
    Нужно скопировать изменения, запустить программу patch, указав в
    качестве её аргумента файл, к которому применяются изменения,
    и всавить скопированный текст:
<table>
<tr class='command'>
<td class='script'>
<pre class='cline'>
\$ patch ~/.bashrc</pre>
</td>
</tr>
</table>
    В данном случае изменения применяются к файлу ~/.bashrc
    </p></li>
    <li><p>
    Для того чтобы получить краткую справочную информацию о команде, 
    нужно подвести к ней мышь. Во всплывающей подсказке появится краткое
    описание команды.
    </p>
    <p>
    Если справочная информация о команде есть, 
    команда выделяется голубым фоном, например: <span class="with_hint" title="главный текстовый редактор Unix">vi</span>.
    Если справочная информация отсутствует,
    команда выделяется розовым фоном, например: <span class="without_hint">notepad.exe</span>.
    Справочная информация может отсутствовать в том случае, 
    если (1) команда введена неверно; (2) если распознавание команды LiLaLo выполнено неверно;
    (3) если информация о команде неизвестна LiLaLo.
    Последнее возможно для редких команд.
    </p></li>
    <li><p>
    Большие, в особенности многострочные, всплывающие подсказки лучше 
    всего показываются браузерами KDE Konqueror, Apple Safari и Microsoft Internet Explorer.
    В браузерах Mozilla и Firefox они отображаются не полностью, 
    а вместо перевода строки выводится специальный символ.
    </p></li>
    <li><p>
    Время ввода команды, показанное в журнале, соответствует времени 
    <i>начала ввода командной строки</i>, которое равно тому моменту, 
    когда на терминале появилось приглашение интерпретатора
    </p></li>
    <li><p>
    Имя терминала, на котором была введена команда, показано в специальном блоке.
    Этот блок показывается только в том случае, если терминал
    текущей команды отличается от терминала предыдущей.
    </p></li>
    <li><p>
    Вывод не интересующих вас в настоящий момент элементов журнала,
    таких как время, имя терминала и других, можно отключить.
    Для этого нужно воспользоваться <a href='#visibility_form'>формой управления журналом</a>
    вверху страницы.
    </p></li>
    <li><p>
    Небольшие комментарии к командам можно вставлять прямо из командной строки.
    Комментарий вводится прямо в командную строку, после символов #^ или #v.
    Символы ^ и v показывают направление выбора команды, к которой относится комментарий:
    ^ - к предыдущей, v - к следующей.
    Например, если в командной строке было введено:
<pre class='cline'>
\$ whoami
</pre>
<pre class='output'>
user
</pre>
<pre class='cline'>
\$ #^ Интересно, кто я?
</pre>
    в журнале это будет выглядеть так:
    
<pre class='cline'>
\$ whoami
</pre>
<pre class='output'>
user
</pre>
<table class='note'><tr><td width='100%' class='note_text'>
<tr> <td> Интересно, кто я?<br/> </td></tr></table> 
    </p></li>
    <li><p>
    Если комментарий содержит несколько строк,
    его можно вставить в журнал следующим образом:
<pre class='cline'>
\$ whoami
</pre>
<pre class='output'>
user
</pre>
<pre class='cline'>
\$ cat > /dev/null #^ Интересно, кто я?
</pre>
<pre class='output'>
Программа whoami выводит имя пользователя, под которым 
мы зарегистрировались в системе.
-
Она не может ответить на вопрос о нашем назначении 
в этом мире.
</pre>
    В журнале это будет выглядеть так:
<table>
<tr class='command'>
<td class='script'>
<pre class='cline'>
\$ whoami</pre>
<pre class='output'>user
</pre>
<table class='note'><tr><td class='note_title'>Интересно, кто я?</td></tr><tr><td width='100%' class='note_text'>
Программа whoami выводит имя пользователя, под которым<br/>
мы зарегистрировались в системе.<br/>
<br/>
Она не может ответить на вопрос о нашем назначении<br/>
в этом мире.<br/>
</td></tr></table>
</td>
</tr>
</table>
    Для разделения нескольких абзацев между собой
    используйте символ "-", один в строке.
    <br/>
</p></li>
    <li><p>
    Комментарии, не относящиеся непосредственно ни к какой из команд, 
    добавляются точно таким же способом, только вместо симолов #^ или #v 
    нужно использовать символы #=
    </p></li>

    <p><li>
    Содержимое файла может быть показано в журнале.
    Для этого его нужно вывести с помощью программы cat.
    Если вывод команды отметить симоволами #!, 
    содержимое файла будет показано в журнале
    в специально отведённой для этого секции.
    </li></p>

    <p>
    <li>
    Для того чтобы вставить скриншот интересующего вас окна в журнал,
    нужно воспользоваться командой l3shot.
    После того как команда вызвана, нужно с помощью мыши выбрать окно, которое
    должно быть в журнале.
    </li>
    </p>

    <p>
    <li>
    Команды в журнале расположены в хронологическом порядке.
    Если две команды давались одна за другой, но на разных терминалах,
    в журнале они будут рядом, даже если они не имеют друг к другу никакого отношения.
<pre>
1
    2
3   
    4
</pre>
    Группы команд, выполненных на разных терминалах, разделяются специальной линией.
    Под этой линией в правом углу показано имя терминала, на котором выполнялись команды.
    Для того чтобы посмотреть команды только одного сенса, 
    нужно щёкнуть по этому названию.
    </li>
    </p>
</ol>
HELP

$Html_About = <<ABOUT;
    <p>
    <a href='http://xgu.ru/lilalo/'>LiLaLo</a> (L3) расшифровывается как Live Lab Log.<br/>
    Программа разработана для повышения эффективности обучения Unix/Linux-системам.<br/>
    (c) Игорь Чубин, 2004-2008<br/>
    </p>
ABOUT
$Html_About.='$Id$ </p>';

$Html_JavaScript = <<JS;
    function getElementsByClassName(Class_Name)
    {
        var Result=new Array();
        var All_Elements=document.all || document.getElementsByTagName('*');
        for (i=0; i<All_Elements.length; i++)
            if (All_Elements[i].className==Class_Name)
        Result.push(All_Elements[i]);
        return Result;
    }
    function ShowHide (name)
    {
        elements=getElementsByClassName(name);
        for(i=0; i<elements.length; i++)
            if (elements[i].style.display == "none")
                elements[i].style.display = "";
            else
                elements[i].style.display = "none";
            //if (elements[i].style.visibility == "hidden")
            //  elements[i].style.visibility = "visible";
            //else
            //  elements[i].style.visibility = "hidden";
    }
    function filter_by_output(text)
    {
        
        var jjj=0;
        
        elements=getElementsByClassName('command');
        for(i=0; i<elements.length; i++) {
            subelems = elements[i].getElementsByTagName('pre');
            for(j=0; j<subelems.length; j++) {
                if (subelems[j].className = 'output') {
                    var str = new String(subelems[j].nodeValue);
                    if (jjj != 1) { 
                        alert(str);
                        jjj=1;
                    }
                    if (str.indexOf(text) >0) 
                        subelems[j].style.display = "none";
                    else
                        subelems[j].style.display = "";

                }
                    
            }
        }       

    }
JS

$SetCursorPosition_JS = <<JS;
function setCursorPosition(oInput,oStart,oEnd) {
    oInput.focus();
    if( oInput.setSelectionRange ) {
        oInput.setSelectionRange(oStart,oEnd);
    } else if( oInput.createTextRange ) {
        var range = oInput.createTextRange();
        range.collapse(true);
        range.moveEnd('character',oEnd);
        range.moveStart('character',oStart);
        range.select();
    }
}
JS

%Search_Machines = (
        "google" =>     {   "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 "<a href='". $Search_Machines{$sm}->{"query"}."$topic'><img width='16' height='16' src='".
                $Search_Machines{$sm}->{"icon"}."' border='0'/></a>";
}




########################################################################################
#
# 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} = <MW>;
    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 .= "<para>$line</para>";
        }
    }
    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;
}