lilalo

view l3-frontend @ 64:3326053f9b23

Порядок таблиц в начале дня; интервалы бездействия
author devi
date Fri Jan 27 09:04:44 2006 +0200 (2006-01-27)
parents 1864df6ccbfe
children 563e3ee69ce8
line source
1 #!/usr/bin/perl -w
3 use IO::Socket;
4 use lib '.';
5 use l3config;
6 use locale;
8 our @Command_Lines;
9 our @Command_Lines_Index;
10 our %Commands_Description;
11 our %Args_Description;
12 our $Mywi_Socket;
13 our %Sessions;
15 # vvv Инициализация переменных выполняется процедурой init_variables
16 our @Day_Name;
17 our @Month_Name;
18 our @Of_Month_Name;
19 our %Search_Machines;
20 our %Elements_Visibility;
21 # ^^^
23 our %Stat;
24 our %CommandsFDistribution; # Сколько раз в журнале встречается какая команда
25 our $table_number=1;
27 my %mywi_cache_for; # Кэш для экономии обращений к mywi
29 sub make_comment;
30 sub make_new_entries_table;
31 sub load_command_lines_from_xml;
32 sub load_sessions_from_xml;
33 sub sort_command_lines;
34 sub process_command_lines;
35 sub init_variables;
36 sub main;
37 sub collapse_list($);
39 sub print_all;
40 sub print_command_lines;
41 sub print_stat;
42 sub print_header;
43 sub print_footer;
45 main();
47 sub main
48 {
49 $| = 1;
51 init_variables();
52 init_config();
54 open_mywi_socket();
55 load_command_lines_from_xml($Config{"backend_datafile"});
56 load_sessions_from_xml($Config{"backend_datafile"});
57 sort_command_lines;
58 process_command_lines;
59 print_all($Config{"output"});
60 close_mywi_socket;
61 }
63 # extract_from_cline
65 # In: $what = commands | args
66 # Out: return ссылка на хэш, содержащий результаты разбора
67 # команда => позиция
69 # Разобрать командную строку $_[1] и возвратить хэш, содержащий
70 # номер первого появление команды в строке:
71 # команда => первая позиция
72 sub extract_from_cline
73 {
74 my $what = $_[0];
75 my $cline = $_[1];
76 my @lists = split /\;/, $cline;
79 my @command_lines = ();
80 for my $command_list (@lists) {
81 push(@command_lines, split(/\|/, $command_list));
82 }
84 my %position_of_command;
85 my %position_of_arg;
86 my $i=0;
87 for my $command_line (@command_lines) {
88 $command_line =~ s@^\s*@@;
89 $command_line =~ /\s*(\S+)\s*(.*)/;
90 if ($1 && $1 eq "sudo" ) {
91 $position_of_command{"$1"}=$i++;
92 $command_line =~ s/\s*sudo\s+//;
93 }
94 if ($command_line !~ m@^\s*\S*/etc/@) {
95 $command_line =~ s@^\s*\S+/@@;
96 }
98 $command_line =~ /\s*(\S+)\s*(.*)/;
99 my $command = $1;
100 my $args = $2;
101 if ($command && !defined $position_of_command{"$command"}) {
102 $position_of_command{"$command"}=$i++;
103 };
104 if ($args) {
105 my @args = split (/\s+/, $args);
106 for my $a (@args) {
107 $position_of_arg{"$a"}=$i++
108 if !defined $position_of_arg{"$a"};
109 };
110 }
111 }
113 if ($what eq "commands") {
114 return \%position_of_command;
115 } else {
116 return \%position_of_arg;
117 }
119 }
124 #
125 # Подпрограммы для работы с mywi
126 #
128 sub open_mywi_socket
129 {
130 $Mywi_Socket = IO::Socket::INET->new(
131 PeerAddr => $Config{mywi_server},
132 PeerPort => $Config{mywi_port},
133 Proto => "tcp",
134 Type => SOCK_STREAM);
135 }
137 sub close_mywi_socket
138 {
139 close ($Mywi_Socket) if $Mywi_Socket ;
140 }
143 sub mywi_client
144 {
145 my $query = $_[0];
146 my $mywi;
148 open_mywi_socket;
149 if ($Mywi_Socket) {
150 local $| = 1;
151 local $/ = "";
152 print $Mywi_Socket $query."\n";
153 $mywi = <$Mywi_Socket>;
154 $mywi = "" if $mywi =~ /nothing app/;
155 }
156 close_mywi_socket;
157 return $mywi;
158 }
160 sub make_comment
161 {
162 my $cline = $_[0];
163 #my $files = $_[1];
165 my @comments;
166 my @commands = keys %{extract_from_cline("commands", $cline)};
167 my @args = keys %{extract_from_cline("args", $cline)};
168 return if (!@commands && !@args);
169 #return "commands=".join(" ",@commands)."; files=".join(" ",@files);
171 # Commands
172 for my $command (@commands) {
173 $command =~ s/'//g;
174 $CommandsFDistribution{$command}++;
175 if (!$Commands_Description{$command}) {
176 $mywi_cache_for{$command} ||= mywi_client ($command) || "";
177 my $mywi = join ("\n", grep(/\([18]|sh|script\)/, split(/\n/, $mywi_cache_for{$command})));
178 $mywi =~ s/\s+/ /;
179 if ($mywi !~ /^\s*$/) {
180 $Commands_Description{$command} = $mywi;
181 }
182 else {
183 next;
184 }
185 }
187 push @comments, $Commands_Description{$command};
188 }
189 return join("&#10;\n", @comments);
191 # Files
192 for my $arg (@args) {
193 $arg =~ s/'//g;
194 if (!$Args_Description{$arg}) {
195 my $mywi;
196 $mywi = mywi_client ($arg);
197 $mywi = join ("\n", grep(/\([5]\)/, split(/\n/, $mywi)));
198 $mywi =~ s/\s+/ /;
199 if ($mywi !~ /^\s*$/) {
200 $Args_Description{$arg} = $mywi;
201 }
202 else {
203 next;
204 }
205 }
207 push @comments, $Args_Description{$arg};
208 }
210 }
212 =cut
213 Процедура load_command_lines_from_xml выполняет загрузку разобранного lab-скрипта
214 из XML-документа в переменную @Command_Lines
216 # In: $datafile имя файла
217 # Out: @CommandLines загруженные командные строки
219 Предупреждение!
220 Процедура не в состоянии обрабатывать XML-документ любой структуры.
221 В действительности файл cache из которого загружаются данные
222 просто напоминает XML с виду.
223 =cut
224 sub load_command_lines_from_xml
225 {
226 my $datafile = $_[0];
228 open (CLASS, $datafile)
229 or die "Can't open file of the class ",$datafile,"\n";
230 local $/;
231 $data = <CLASS>;
232 close(CLASS);
234 for $command ($data =~ m@<command>(.*?)</command>@sg) {
235 my %cl;
236 while ($command =~ m@<([^>]*?)>(.*?)</\1>@sg) {
237 $cl{$1} = $2;
238 }
239 push @Command_Lines, \%cl;
240 }
241 }
243 sub load_sessions_from_xml
244 {
245 my $datafile = $_[0];
247 open (CLASS, $datafile)
248 or die "Can't open file of the class ",$datafile,"\n";
249 local $/;
250 my $data = <CLASS>;
251 close(CLASS);
253 for my $session ($data =~ m@<session>(.*?)</session>@sg) {
254 my %session;
255 while ($session =~ m@<([^>]*?)>(.*?)</\1>@sg) {
256 $session{$1} = $2;
257 }
258 $Sessions{$session{local_session_id}} = \%session;
259 }
260 }
263 # sort_command_lines
264 # In: @Command_Lines
265 # Out: @Command_Lies_Index
267 sub sort_command_lines
268 {
270 my @index;
271 for (my $i=0;$i<=$#Command_Lines;$i++) {
272 $index[$i]=$i;
273 }
275 @Command_Lines_Index = sort {
276 $Command_Lines[$index[$a]]->{"time"} <=> $Command_Lines[$index[$b]]->{"time"}
277 } @index;
279 }
281 ##################
282 # process_command_lines
283 #
284 # Обрабатываются командные строки @Command_Lines
285 # Для каждой строки определяется:
286 # class класс
287 # note комментарий
288 #
289 # In: @Command_Lines_Index
290 # In-Out: @Command_Lines
292 sub process_command_lines
293 {
294 for my $i (@Command_Lines_Index) {
295 my $cl = \$Command_Lines[$i];
297 next if !$cl;
299 $$cl->{err} ||=0;
301 # Класс команды
303 $$cl->{"class"} = $$cl->{"err"} eq 130 ? "interrupted"
304 : $$cl->{"err"} eq 127 ? "mistyped"
305 : $$cl->{"err"} ? "wrong"
306 : "normal";
308 if ($$cl->{"cline"} =~ /[^|`]\s*sudo/
309 || $$cl->{"uid"} eq 0) {
310 $$cl->{"class"}.="_root";
311 }
314 #Обработка пометок
315 # Если несколько пометок (notes) идут подряд,
316 # они все объединяются
318 if ($$cl->{cline}=~ m@cat[^#]*#([\^=v])\s*(.*)@) {
320 my $note_operator = $1;
321 my $note_title = $2;
323 if ($note_operator eq "=") {
324 $$cl->{"class"} = "note";
325 $$cl->{"note"} = $$cl->{"output"};
326 $$cl->{"note_title"} = $2;
327 }
328 else {
329 my $j = $i;
330 if ($note_operator eq "^") {
331 $j--;
332 $j-- while ($j >=0 && (!$Command_Lines[$j] || $Command_Lines[$j]->{tty} ne $$cl->{tty}));
333 }
334 elsif ($note_operator eq "v") {
335 $j++;
336 $j++ while ($j <= @Command_Lines && (!$Command_Lines[$j] || $Command_Lines[$j]->{tty} ne $$cl->{tty}));
337 }
338 $Command_Lines[$j]->{note_title}=$note_title;
339 $Command_Lines[$j]->{note}.=$$cl->{output};
340 $$cl=0;
341 }
342 }
343 elsif ($$cl->{cline}=~ /#([\^=v])(.*)/) {
345 my $note_operator = $1;
346 my $note_text = $2;
348 if ($note_operator eq "=") {
349 $$cl->{"class"} = "note";
350 $$cl->{"note"} = $note_text;
351 }
352 else {
353 my $j=$i;
354 if ($note_operator eq "^") {
355 $j--;
356 $j-- while ($j >=0 && (!$Command_Lines[$j] || $Command_Lines[$j]->{tty} ne $$cl->{tty}));
357 }
358 elsif ($note_operator eq "v") {
359 $j++;
360 $j++ while ($j <= @Command_Lines && $Command_Lines[$j]->{tty} ne $$cl->{tty} || !$Command_Lines[$j]);
361 }
362 $Command_Lines[$j]->{note}.="$note_text\n";
363 $$cl=0;
364 }
365 }
366 }
368 }
371 =cut
372 Процедура print_command_lines выводит HTML-представление
373 разобранного lab-скрипта.
375 Разобранный lab-скрипт должен находиться в массиве @Command_Lines
376 =cut
378 sub print_command_lines
379 {
381 my @toc; # Оглавление
382 my $note_number=0;
384 my $result = q();
385 my $this_day_resut = q();
387 my $cl;
388 my $last_tty="";
389 my $last_day=q();
390 my $last_wday=q();
391 my $in_range=0;
393 my $current_command=0;
395 my @known_commands;
397 my %filter;
399 if ($Config{filter}) {
400 # Инициализация фильтра
401 for (split /&/,$Config{filter}) {
402 my ($var, $val) = split /=/;
403 $filter{$var} = $val || "";
404 }
405 }
407 #$result = "Filter=".$Config{filter}."\n";
409 $Stat{LastCommand} ||= 0;
410 $Stat{TotalCommands} ||= 0;
411 $Stat{ErrorCommands} ||= 0;
412 $Stat{MistypedCommands} ||= 0;
414 my %new_entries_of = (
415 "1 1" => "программы пользователя",
416 "2 8" => "программы администратора",
417 "3 sh" => "команды интерпретатора",
418 "4 script"=> "скрипты",
419 );
421 COMMAND_LINE:
422 for my $k (@Command_Lines_Index) {
424 my $cl=$Command_Lines[$Command_Lines_Index[$current_command++]];
425 next unless $cl;
427 # Пропускаем команды, с одинаковым временем
428 # Это не совсем правильно.
429 # Возможно, что это команды, набираемые с помощью <completion>
430 # или запомненные с помощью <ctrl-c>
432 next if $Stat{LastCommand} == $cl->{time};
434 # Пропускаем строки, которые противоречат фильтру
435 # Если у нас недостаточно информации о том, подходит строка под фильтр или нет,
436 # мы её выводим
438 #$result .= "before<br/>";
439 for my $filter_key (keys %filter) {
440 #$result .= "undefined local session id<br/>\n" if !defined($cl->{local_session_id});
441 #$result .= "undefined filter key $filter_key <br/>\n" if !defined($Sessions{$cl->{local_session_id}}->{$filter_key});
442 #$result .= $Sessions{$cl->{local_session_id}}->{$filter_key}." != ".$filter{$filter_key};
443 next COMMAND_LINE if
444 defined($cl->{local_session_id})
445 && defined($Sessions{$cl->{local_session_id}}->{$filter_key})
446 && $Sessions{$cl->{local_session_id}}->{$filter_key} ne $filter{$filter_key};
447 }
449 # Набираем статистику
450 # Хэш %Stat
452 $Stat{FirstCommand} = $cl->{time} unless $Stat{FirstCommand};
453 if ($cl->{time} - $Stat{LastCommand} < $Config{stat_inactivity_interval}) {
454 $Stat{TotalTime} += $cl->{time} - $Stat{LastCommand}
455 }
456 my $seconds_since_last_command = $cl->{time} - $Stat{LastCommand};
457 $Stat{LastCommand} = $cl->{time};
458 $Stat{TotalCommands}++;
461 # Пропускаем строки, выходящие за границу "signature",
462 # при условии, что границы указаны
463 # Пропускаем неправильные/прерванные/другие команды
464 if ($Config{"from"} && $cl->{"cline"} =~ /$Config{"signature"}\s*$Config{"from"}/) {
465 $in_range=1;
466 next;
467 }
468 if ($Config{"to"} && $cl->{"cline"} =~ /$Config{"signature"}\s*$Config{"to"}/) {
469 $in_range=0;
470 next;
471 }
472 next if ($Config{"from"} && $Config{"to"} && !$in_range)
473 || ($Config{"skip_empty"} =~ /^y/i && $cl->{"cline"} =~ /^\s*$/ )
474 || ($Config{"skip_wrong"} =~ /^y/i && $cl->{"err"} != 0)
475 || ($Config{"skip_interrupted"} =~ /^y/i && $cl->{"err"} == 130);
477 if ($cl->{class} eq "note") {
478 my $note = $cl->{note};
479 $note = join ("\n", map ("<p>$_</p>", split (/-\n/, $note)));
480 $note =~ s@(http:[a-zA-Z.0-9/?\_%-]*)@<a href='$1'>$1</a>@g;
481 $note =~ s@(www\.[a-zA-Z.0-9/?\_%-]*)@<a href='$1'>$1</a>@g;
482 $this_day_result .= "<tr><td colspan='6'>"
483 . "<h4 id='note$note_number'>".$cl->{note_title}."</h4>" if $cl->{note_title}
484 . "".$note."<p/><p/></td></tr>";
486 if ($cl->{note_title}) {
487 push @{$toc[@toc]},"<a href='#note$note_number'>".$cl->{note_title}."</a>";
488 $note_number++;
489 }
490 next;
491 }
494 my $output="";
495 # Выводим <head_lines> верхних строк
496 # и <tail_lines> нижних строк,
497 # если эти параметры существуют
499 my @lines = split '\n', $cl->{"output"};
500 if (($Config{"head_lines"} || $Config{"tail_lines"})
501 && $#lines > $Config{"head_lines"} + $Config{"tail_lines"} ) {
503 for (my $i=0; $i<= $#lines && $i < $Config{"head_lines"}; $i++) {
504 $output .= $lines[$i]."\n";
505 }
506 $output .= $Config{"skip_text"}."\n";
508 my $start_line=$#lines-$Config{"tail_lines"}+1;
509 for ($i=$start_line; $i<= $#lines; $i++) {
510 $output .= $lines[$i]."\n";
511 }
512 }
513 else {
514 $output .= $cl->{"output"};
515 }
517 #
518 ##
519 ## Начинается собственно вывод
520 ##
521 #
523 my ($sec,$min,$hour,$day,$mon,$year,$wday,$yday,$isdst) = localtime($cl->{time});
525 # Добавляем спереди 0 для удобочитаемости
526 $min = "0".$min if $min =~ /^.$/;
527 $hour = "0".$hour if $hour =~ /^.$/;
528 $sec = "0".$sec if $sec =~ /^.$/;
530 $class=$cl->{"class"};
531 $Stat{ErrorCommands}++ if $class =~ /wrong/;
532 $Stat{MistypedCommands}++ if $class =~ /mistype/;
535 # DAY CHANGE
536 if ( $last_day ne $day) {
537 if ($last_day) {
539 # Вычисляем разность множеств.
540 # Что-то вроде этого, если бы так можно было писать:
541 # @new_commands = keys %CommandsFDistribution - @known_commands;
544 $result .= "<h3 id='day$last_day'>".$Day_Name[$last_wday]."</h3>";
548 for my $entry_class (sort keys %new_entries_of) {
549 my $new_commands_section = make_new_entries_table($entry_class=~/[0-9]+\s+(.*)/, \@known_commands);
551 my $table_caption = "Таблица ".$table_number++.". ".$Day_Name[$last_wday].". Новые ".$new_entries_of{$entry_class};
552 if ($new_commands_section) {
553 $result .= "<table class='new_commands_table' width='100%'>"
554 . "<tr class='new_commands_caption'><td colspan='2' align='right'>$table_caption</td></tr>"
555 . "<tr class='new_commands_header'><td width=100>Команда</td><td>Описание</td></tr>"
556 . $new_commands_section
557 . "</table>"
558 }
560 }
561 @known_commands = keys %CommandsFDistribution;
562 $result .= "<table width='100%'>\n";
563 $result .= $this_day_result;
564 $result .= "</table>";
565 }
567 push @toc, "<a href='#day$day'>".$Day_Name[$wday]."</a>\n";
568 $last_day=$day;
569 $last_wday=$wday;
570 $this_day_result = q();
571 }
572 elsif ($seconds_since_last_command > 600) {
573 my $height = $seconds_since_last_command > 1200 ? 100: 60;
574 my $minutes_passed = int($seconds_since_last_command/60);
575 my $minutes_word = $minutes_passed % 10 == 1 ? "минута":
576 $minutes_passed % 10 == 0 ? "минут" :
577 $minutes_passed % 10 > 4 ? "минут" :
578 "минуты";
580 $this_day_result .= "<tr height='60'>"
581 . "<td colspan='4' height='$height'>"
582 . "<font size='-1'>"
583 . "прошло ".$minutes_passed." ".$minutes_word
584 . "</font>"
585 . "</td></tr>\n";
586 }
588 $this_day_result .= "<tr class='command'>\n";
591 # CONSOLE CHANGE
592 if ( $last_tty ne $cl->{"tty"}) {
593 my $tty = $cl->{"tty"};
594 $this_day_result .= "<td colspan='6'>"
595 ."<table><tr><td class='ttychange' width='140' align='center'>"
596 . $tty
597 ."</td></tr></table>"
598 ."</td></tr><tr>";
599 $last_tty=$cl->{"tty"};
600 }
602 # TIME
603 $this_day_result .= $Config{"show_time"} =~ /^y/i
604 ? "<td valign='top' class='time' width='$Config{time_width}'>$hour:$min:$sec</td>"
605 : "<td width='0'/>";
607 # CLASS
608 $this_day_result .= "<td width='20' valign='top'>F</td>";
610 # COMMAND
611 my $hint = make_comment($cl->{"cline"});
613 my $cline;
614 $cline = $cl->{"prompt"}.$cl->{"cline"};
615 $cline =~ s/\n//;
617 $cline = "<span title='$hint' class='with_hint'>$cline</span>" if $hint;
618 $cline = "<span class='without_hint'>$cline</span>" if !$hint;
620 $this_day_result .= "<td class='script'>\n";
621 $this_day_result .= "<pre class='${class}_cline'>\n" . $cline . "</pre>\n";
623 # OUTPUT
624 my $last_command = $cl->{"last_command"};
625 if (!(
626 $Config{"suppress_editors"} =~ /^y/i && grep ($_ eq $last_command, @{$Config{"editors"}}) ||
627 $Config{"suppress_pagers"} =~ /^y/i && grep ($_ eq $last_command, @{$Config{"pagers"}}) ||
628 $Config{"suppress_terminal"}=~ /^y/i && grep ($_ eq $last_command, @{$Config{"terminal"}})
629 )) {
630 $this_day_result .= "<pre class='".$class."_output'>" . $output . "</pre>\n";
631 }
633 # DIFF
634 if ( $Config{"show_diffs"} =~ /^y/i && $cl->{"diff"}) {
635 $this_day_result .= "<table><tr><td width='5'/><td class='diff'><pre>"
636 . $cl->{"diff"}
637 . "</pre></td></tr></table>";
638 }
640 #NOTES
641 if ( $Config{"show_notes"} =~ /^y/i && $cl->{"note"}) {
642 my $note=$cl->{"note"};
643 $note =~ s/\n/<br\/>\n/msg;
644 if (not $note =~ s@(http:[a-zA-Z.0-9/_?%-]*)@<a href='$1'>$1</a>@g) {
645 $note =~ s@(www\.[a-zA-Z.0-9/_?%-]*)@<a href='$1'>$1</a>@g;
646 };
647 # Ширину пока не используем
648 # $this_day_result .= "<table width='$Config{note_width}' class='note'>";
649 $this_day_result .= "<table class='note'>";
650 $this_day_result .= "<tr><td class='note_title'>".$cl->{note_title}."</td></tr>" if $cl->{note_title};
651 $this_day_result .= "<tr><td width='100%' class='note_text'>".$note."</td></tr>";
652 $this_day_result .= "</table>\n";
653 }
655 # COMMENT
656 if ( $Config{"show_comments"} =~ /^y/i) {
657 my $comment = make_comment($cl->{"cline"});
658 if ($comment) {
659 $this_day_result .= "<table width='$Config{comment_width}'><tr><td width='5'/><td>"
660 . "<table class='note' width='100%'>"
661 . $comment
662 . "</table>\n"
663 . "</td></tr></table>";
664 }
665 }
667 # Вывод очередной команды окончен
668 $this_day_result .= "</td>\n";
669 $this_day_result .= "</tr>\n";
670 }
671 last: {
672 $result .= "<h3 id='day$last_day'>".$Day_Name[$last_wday]."</h3>";
674 for my $entry_class (keys %new_entries_of) {
675 my $new_commands_section = make_new_entries_table("$entry_class", \@known_commands);
676 @known_commands = keys %CommandsFDistribution;
678 my $table_caption = "Таблица ".$table_number++.". Новые ".$new_entries_of{$entry_class}. ". ".$Day_Name[$last_wday];
679 if ($new_commands_section) {
680 $result .= "<table class='new_commands_table'>"
681 . "<tr class='new_commands_caption'><td colspan='2' align='right'>$table_caption</td></tr>"
682 . "<tr class='new_commands_header'><td>Команда</td><td>Описание</td></tr>"
683 . $new_commands_section
684 . "</table>"
685 ;
686 }
688 }
690 $result .= "<table width='100%'>\n";
691 $result .= $this_day_result;
692 $result .= "</table>";
693 }
695 return ($result, collapse_list (\@toc));
697 }
699 sub make_new_entries_table
700 {
701 my $entries_class = shift;
702 my @known_commands = @{$_[0]};
704 my %count;
705 my @new_commands = ();
706 for my $c (keys %CommandsFDistribution, @known_commands) {
707 $count{$c}++
708 }
709 for my $c (keys %CommandsFDistribution) {
710 push @new_commands, $c if $count{$c} != 2;
711 }
714 my $new_commands_section;
715 if (@new_commands){
716 my $hint;
717 for my $c (reverse sort { $CommandsFDistribution{$a} <=> $CommandsFDistribution{$b} } @new_commands) {
718 $hint = make_comment($c);
719 my ($command, $hint) = $hint =~ m/(.*?) \s*- \s*(.*)/;
720 next unless $command =~ s/\($entries_class\)//i;
721 $new_commands_section .= "<tr><td valign='top'>$command</td><td>$hint</td></tr>" if $hint;
722 }
723 }
724 return $new_commands_section;
725 }
728 #############
729 # print_all
730 #
731 #
732 #
733 # In: $_[0] output_filename
734 # Out:
737 sub print_all
738 {
739 my $output_filename=$_[0];
741 my $result;
742 my ($command_lines,$toc) = print_command_lines;
744 $result = print_header($toc);
745 $result.= "<h2 id='log'>Журнал</h2>" . $command_lines;
746 $result.= "<h2 id='stat'>Статистика</h2>" . print_stat;
747 $result.= "<h2 id='help'>Справка</h2>" . $Html_Help . "<br/>";
748 $result.= "<h2 id='about'>О программе</h2>". $Html_About. "<br/>";
749 $result.= print_footer;
751 if ($output_filename eq "-") {
752 print $result;
753 }
754 else {
755 open(OUT, ">", $output_filename)
756 or die "Can't open $output_filename for writing\n";
757 print OUT $result;
758 close(OUT);
759 }
760 }
762 #############
763 # print_header
764 #
765 #
766 #
767 # In: $_[0] Содержание
768 # Out: Распечатанный заголовок
770 sub print_header
771 {
772 my $toc = $_[0];
773 my $course_name = $Config{"course-name"};
774 my $course_code = $Config{"course-code"};
775 my $course_date = $Config{"course-date"};
776 my $course_center = $Config{"course-center"};
777 my $course_trainer = $Config{"course-trainer"};
778 my $course_student = $Config{"course-student"};
780 my $title = "Журнал лабораторных работ";
781 $title .= " -- ".$course_student if $course_student;
782 if ($course_date) {
783 $title .= " -- ".$course_date;
784 $title .= $course_code ? "/".$course_code
785 : "";
786 }
787 else {
788 $title .= " -- ".$course_code if $course_code;
789 }
791 # Управляющая форма
792 my $control_form .= "<table id='visibility_form' class='visibility_form'><tr><td>Видимые элементы</TD></tr><tr><td><form>\n";
793 for my $element (keys %Elements_Visibility)
794 {
795 my @e = split /\s+/, $element;
796 my $showhide = join "", map { "ShowHide('$_');" } @e ;
797 $control_form .= "<input type='checkbox' name='$e[0]' onclick=\"$showhide\" checked>".
798 $Elements_Visibility{$element}.
799 "</input><br>\n";
800 }
801 $control_form .= "</form></td></tr></table>\n";
803 my $result;
804 $result = <<HEADER;
805 <html>
806 <head>
807 <meta content='text/html; charset=utf-8' http-equiv='Content-Type' />
808 <link rel='stylesheet' href='$Config{frontend_css}' type='text/css'/>
809 <title>$title</title>
810 </head>
811 <body>
812 <script>
813 $Html_JavaScript
814 </script>
816 <!-- vvv Tigra Hints vvv -->
817 <script language="JavaScript" src="/tigra/hints.js"></script>
818 <script language="JavaScript" src="/tigra/hints_cfg.js"></script>
819 <style>
820 /* a class for all Tigra Hints boxes, TD object */
821 .hintsClass
822 {text-align: center; font-family: Verdana, Arial, Helvetica; padding: 0px 0px 0px 0px;}
823 /* this class is used by Tigra Hints wrappers */
824 .row
825 {background: white;}
826 </style>
827 <!-- ^^^ Tigra Hints ^^^ -->
830 <h1 onmouseover="myHint.show('1')" onmouseout="myHint.hide()">Журнал лабораторных работ</h1>
831 HEADER
832 if ( $course_student
833 || $course_trainer
834 || $course_name
835 || $course_code
836 || $course_date
837 || $course_center) {
838 $result .= "<p>";
839 $result .= "Выполнил $course_student<br/>" if $course_student;
840 $result .= "Проверил $course_trainer <br/>" if $course_trainer;
841 $result .= "Курс " if $course_name
842 || $course_code
843 || $course_date;
844 $result .= "$course_name " if $course_name;
845 $result .= "($course_code)" if $course_code;
846 $result .= ", $course_date<br/>" if $course_date;
847 $result .= "Учебный центр $course_center <br/>" if $course_center;
848 $result .= "</p>";
849 }
851 $result .= <<HEADER;
852 <table width='100%'>
853 <tr>
854 <td width='*'>
856 <table border=0 id='toc' class='toc'>
857 <tr>
858 <td>
859 <div class='toc_title'>Содержание</div>
860 <ul>
861 <li><a href='#log'>Журнал</a></li>
862 <ul>$toc</ul>
863 <li><a href='#stat'>Статистика</a></li>
864 <li><a href='#help'>Справка</a></li>
865 <li><a href='#about'>О программе</a></li>
866 </ul>
867 </td>
868 </tr>
869 </table>
871 </td>
872 <td valign='top' width=200>$control_form</td>
873 </tr>
874 </table>
875 HEADER
877 return $result;
878 }
881 #############
882 # print_footer
883 #
884 #
885 #
886 #
887 #
889 sub print_footer
890 {
891 return "</body>\n</html>\n";
892 }
897 #############
898 # print_stat
899 #
900 #
901 #
902 # In:
903 # Out:
905 sub print_stat
906 {
907 %StatNames = (
908 FirstCommand => "Время первой команды журнала",
909 LastCommand => "Время последней команды журнала",
910 TotalCommands => "Количество командных строк в журнале",
911 ErrorsPercentage => "Процент команд с ненулевым кодом завершения, %",
912 MistypesPercentage => "Процент синтаксически неверно набранных команд, %",
913 TotalTime => "Суммарное время работы с терминалом <sup><font size='-2'>*</font></sup>, час",
914 CommandsPerTime => "Количество командных строк в единицу времени, команда/мин",
915 CommandsFrequency => "Частота использования команд",
916 RareCommands => "Частота использования этих команд < 0.5%",
917 );
918 @StatOrder = (
919 FirstCommand,
920 LastCommand,
921 TotalCommands,
922 ErrorsPercentage,
923 MistypesPercentage,
924 TotalTime,
925 CommandsPerTime,
926 CommandsFrequency,
927 RareCommands,
928 );
930 # Подготовка статистики к выводу
931 # Некоторые значения пересчитываются!
932 # Дальше их лучше уже не использовать!!!
934 my %CommandsFrequency = %CommandsFDistribution;
936 $Stat{TotalTime} ||= 0;
937 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($Stat{FirstCommand} || 0);
938 $Stat{FirstCommand} = sprintf "%02i:%02i:%02i %04i-%2i-%2i", $hour, $min, $sec, $year+1900, $mon+1, $mday;
939 ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($Stat{LastCommand} || 0);
940 $Stat{LastCommand} = sprintf "%02i:%02i:%02i %04i-%2i-%2i", $hour, $min, $sec, $year+1900, $mon+1, $mday;
941 if ($Stat{TotalCommands}) {
942 $Stat{ErrorsPercentage} = sprintf "%5.2f", $Stat{ErrorCommands}*100/$Stat{TotalCommands};
943 $Stat{MistypesPercentage} = sprintf "%5.2f", $Stat{MistypedCommands}*100/$Stat{TotalCommands};
944 }
945 $Stat{CommandsPerTime} = sprintf "%5.2f", $Stat{TotalCommands}*60/$Stat{TotalTime}
946 if $Stat{TotalTime};
947 $Stat{TotalTime} = sprintf "%5.2f", $Stat{TotalTime}/60/60;
949 my $total_commands=0;
950 for $command (keys %CommandsFrequency){
951 $total_commands += $CommandsFrequency{$command};
952 }
953 if ($total_commands) {
954 for $command (reverse sort {$CommandsFrequency{$a} <=> $CommandsFrequency{$b}} keys %CommandsFrequency){
955 my $command_html;
956 my $percentage = sprintf "%5.2f",$CommandsFrequency{$command}*100/$total_commands;
957 if ($percentage < 0.5) {
958 my $hint = make_comment($command);
959 $command_html = "$command";
960 $command_html = "<span title='$hint' class='with_hint'>$command_html</span>" if $hint;
961 $command_html = "<span class='without_hint'>$command_html</span>" if not $hint;
962 my $command_html = "<tt>$command_html</tt>";
963 $Stat{RareCommands} .= $command_html."<sub><font size='-2'>".$CommandsFrequency{$command}."</font></sub> , ";
964 }
965 else {
966 my $hint = make_comment($command);
967 $command_html = "$command";
968 $command_html = "<span title='$hint' class='with_hint'>$command_html</span>" if $hint;
969 $command_html = "<span class='without_hint'>$command_html</span>" if not $hint;
970 my $command_html = "<tt>$command_html</tt>";
971 $percentage = sprintf "%5.2f",$percentage;
972 $Stat{CommandsFrequency} .= "<tr><td>".$command_html."</td><td>".$CommandsFrequency{$command}."</td>".
973 "<td>|".("="x int($CommandsFrequency{$command}*100/$total_commands))."| $percentage%</td></tr>";
974 }
975 }
976 $Stat{CommandsFrequency} = "<table>".$Stat{CommandsFrequency}."</table>";
977 $Stat{RareCommands} =~ s/, $// if $Stat{RareCommands};
978 }
980 my $result = q();
981 for my $stat (@StatOrder) {
982 next unless $Stat{"$stat"};
983 $result .= "<tr valign='top'><td width='300'>".$StatNames{"$stat"}."</td><td>".$Stat{"$stat"}."</td></tr>"
984 }
985 $result = "<table>$result</table>"
986 . "<font size='-2'>____<br/>*) Интервалы неактивности длительностью "
987 . ($Config{stat_inactivity_interval}/60)
988 . " минут и более не учитываются</font></br>";
990 return $result;
991 }
994 sub collapse_list($)
995 {
996 my $res = "";
997 for my $elem (@{$_[0]}) {
998 if (ref $elem eq "ARRAY") {
999 $res .= "<ul>".collapse_list($elem)."</ul>";
1001 else
1003 $res .= "<li>".$elem."</li>";
1006 return $res;
1012 sub init_variables
1014 $Html_Help = <<HELP;
1015 Для того чтобы использовать LiLaLo, не нужно знать ничего особенного:
1016 всё происходит само собой.
1017 Однако, чтобы ведение и последующее использование журналов
1018 было как можно более эффективным, желательно иметь в виду следующее:
1019 <ol>
1020 <li><p>
1021 В журнал автоматически попадают все команды, данные в любом терминале системы.
1022 </p></li>
1023 <li><p>
1024 Для того чтобы убедиться, что журнал на текущем терминале ведётся,
1025 и команды записываются, дайте команду w.
1026 В поле WHAT, соответствующем текущему терминалу,
1027 должна быть указана программа script.
1028 </p></li>
1029 <li><p>
1030 Команды, при наборе которых были допущены синтаксические ошибки,
1031 выводятся перечёркнутым текстом:
1032 <table>
1033 <tr class='command'>
1034 <td class='script'>
1035 <pre class='mistyped_cline'>
1036 \$ l s-l</pre>
1037 <pre class='mistyped_output'>bash: l: command not found
1038 </pre>
1039 </td>
1040 </tr>
1041 </table>
1042 <br/>
1043 </p></li>
1044 <li><p>
1045 Если код завершения команды равен нулю,
1046 команда была выполнена без ошибок.
1047 Команды, код завершения которых отличен от нуля, выделяются цветом.
1048 <table>
1049 <tr class='command'>
1050 <td class='script'>
1051 <pre class='wrong_cline'>
1052 \$ test 5 -lt 4</pre>
1053 </pre>
1054 </td>
1055 </tr>
1056 </table>
1057 Обратите внимание на то, что код завершения команды может быть отличен от нуля
1058 не только в тех случаях, когда команда была выполнена с ошибкой.
1059 Многие команды используют код завершения, например, для того чтобы показать результаты проверки
1060 <br/>
1061 </p></li>
1062 <li><p>
1063 Команды, ход выполнения которых был прерван пользователем, выделяются цветом.
1064 <table>
1065 <tr class='command'>
1066 <td class='script'>
1067 <pre class='interrupted_cline'>
1068 \$ find / -name abc</pre>
1069 <pre class='interrupted_output'>find: /home/devi-orig/.gnome2: Keine Berechtigung
1070 find: /home/devi-orig/.gnome2_private: Keine Berechtigung
1071 find: /home/devi-orig/.nautilus/metafiles: Keine Berechtigung
1072 find: /home/devi-orig/.metacity: Keine Berechtigung
1073 find: /home/devi-orig/.inkscape: Keine Berechtigung
1074 ^C
1075 </pre>
1076 </td>
1077 </tr>
1078 </table>
1079 <br/>
1080 </p></li>
1081 <li><p>
1082 Команды, выполненные с привилегиями суперпользователя,
1083 выделяются слева красной чертой.
1084 <table>
1085 <tr class='command'>
1086 <td class='script'>
1087 <pre class='_root_cline'>
1088 # id</pre>
1089 <pre class='_root_output'>
1090 uid=0(root) gid=0(root) Gruppen=0(root)
1091 </pre>
1092 </td>
1093 </tr>
1094 </table>
1095 <br/>
1096 </p></li>
1097 <li><p>
1098 Изменения, внесённые в текстовый файл с помощью редактора,
1099 запоминаются и показываются в журнале в формате ed.
1100 Строки, начинающиеся символом "&lt;", удалены, а строки,
1101 начинающиеся символом "&gt;" -- добавлены.
1102 <table>
1103 <tr class='command'>
1104 <td class='script'>
1105 <pre class='cline'>
1106 \$ vi ~/.bashrc</pre>
1107 <table><tr><td width='5'/><td class='diff'><pre>2a3,5
1108 &gt; if [ -f /usr/local/etc/bash_completion ]; then
1109 &gt; . /usr/local/etc/bash_completion
1110 &gt; fi
1111 </pre></td></tr></table></td>
1112 </tr>
1113 </table>
1114 <br/>
1115 </p></li>
1116 <li><p>
1117 Для того чтобы изменить файл в соответствии с показанными в диффшоте
1118 изменениями, можно воспользоваться командой patch.
1119 Нужно скопировать изменения, запустить программу patch, указав в
1120 качестве её аргумента файл, к которому применяются изменения,
1121 и всавить скопированный текст:
1122 <table>
1123 <tr class='command'>
1124 <td class='script'>
1125 <pre class='cline'>
1126 \$ patch ~/.bashrc</pre>
1127 </td>
1128 </tr>
1129 </table>
1130 В данном случае изменения применяются к файлу ~/.bashrc
1131 </p></li>
1132 <li><p>
1133 Для того чтобы получить краткую справочную информацию о команде,
1134 нужно подвести к ней мышь. Во всплывающей подсказке появится краткое
1135 описание команды.
1136 </p>
1137 <p>
1138 Если справочная информация о команде есть,
1139 команда выделяется голубым фоном, например: <span class="with_hint" title="главный текстовый редактор Unix">vi</span>.
1140 Если справочная информация отсутствует,
1141 команда выделяется розовым фоном, например: <span class="without_hint">notepad.exe</span>.
1142 Справочная информация может отсутствовать в том случае,
1143 если (1) команда введена неверно; (2) если распознавание команды LiLaLo выполнено неверно;
1144 (3) если информация о команде неизвестна LiLaLo.
1145 Последнее возможно для редких команд.
1146 </p></li>
1147 <li><p>
1148 Большие, в особенности многострочные, всплывающие подсказки лучше
1149 всего показываются браузерами KDE Konqueror, Apple Safari и Microsoft Internet Explorer.
1150 В браузерах Mozilla и Firefox они отображаются не полностью,
1151 а вместо перевода строки выводится специальный символ.
1152 </p></li>
1153 <li><p>
1154 Время ввода команды, показанное в журнале, соответствует времени
1155 <i>начала ввода командной строки</i>, которое равно тому моменту,
1156 когда на терминале появилось приглашение интерпретатора
1157 </p></li>
1158 <li><p>
1159 Имя терминала, на котором была введена команда, показано в специальном блоке.
1160 Этот блок показывается только в том случае, если терминал
1161 текущей команды отличается от терминала предыдущей.
1162 </p></li>
1163 <li><p>
1164 Вывод не интересующих вас в настоящий момент элементов журнала,
1165 таких как время, имя терминала и других, можно отключить.
1166 Для этого нужно воспользоваться <a href='#visibility_form'>формой управления журналом</a>
1167 вверху страницы.
1168 </p></li>
1169 <li><p>
1170 Небольшие комментарии к командам можно вставлять прямо из командной строки.
1171 Комментарий вводится прямо в командную строку, после символов #^ или #v.
1172 Символы ^ и v показывают направление выбора команды, к которой относится комментарий:
1173 ^ - к предыдущей, v - к следующей.
1174 Например, если в командной строке было введено:
1175 <pre class='cline'>
1176 \$ whoami
1177 </pre>
1178 <pre class='output'>
1179 user
1180 </pre>
1181 <pre class='cline'>
1182 \$ #^ Интересно, кто я?
1183 </pre>
1184 в журнале это будет выглядеть так:
1186 <pre class='cline'>
1187 \$ whoami
1188 </pre>
1189 <pre class='output'>
1190 user
1191 </pre>
1192 <table class='note'><tr><td width='100%' class='note_text'>
1193 <tr> <td> Интересно, кто я?<br/> </td></tr></table>
1194 </p></li>
1195 <li><p>
1196 Если комментарий содержит несколько строк,
1197 его можно вставить в журнал следующим образом:
1198 <pre class='cline'>
1199 \$ whoami
1200 </pre>
1201 <pre class='output'>
1202 user
1203 </pre>
1204 <pre class='cline'>
1205 \$ cat > /dev/null #^ Интересно, кто я?
1206 </pre>
1207 <pre class='output'>
1208 Программа whoami выводит имя пользователя, под которым
1209 мы зарегистрировались в системе.
1211 Она не может ответить на вопрос о нашем назначении
1212 в этом мире.
1213 </pre>
1214 В журнале это будет выглядеть так:
1215 <table>
1216 <tr class='command'>
1217 <td class='script'>
1218 <pre class='cline'>
1219 \$ whoami</pre>
1220 <pre class='output'>user
1221 </pre>
1222 <table class='note'><tr><td class='note_title'>Интересно, кто я?</td></tr><tr><td width='100%' class='note_text'>
1223 Программа whoami выводит имя пользователя, под которым<br/>
1224 мы зарегистрировались в системе.<br/>
1225 <br/>
1226 Она не может ответить на вопрос о нашем назначении<br/>
1227 в этом мире.<br/>
1228 </td></tr></table>
1229 </td>
1230 </tr>
1231 </table>
1232 Для разделения нескольких абзацев между собой
1233 используйте символ "-", один в строке.
1234 <br/>
1235 </p></li>
1236 <li><p>
1237 Комментарии, не относящиеся непосредственно ни к какой из команд,
1238 добавляются точно таким же способом, только вместо симолов #^ или #v
1239 нужно использовать символы #=
1240 </p></li>
1241 </ol>
1242 HELP
1244 $Html_About = <<ABOUT;
1245 <p>
1246 LiLaLo (L3) расшифровывается как Live Lab Log.<br/>
1247 Программа разработана для повышения эффективности обучения Unix/Linux-системам.<br/>
1248 (c) Игорь Чубин, 2004-2005<br/>
1249 </p>
1250 ABOUT
1251 $Html_About.='$Id$ </p>';
1253 $Html_JavaScript = <<JS;
1254 function getElementsByClassName(Class_Name)
1256 var Result=new Array();
1257 var All_Elements=document.all || document.getElementsByTagName('*');
1258 for (i=0; i<All_Elements.length; i++)
1259 if (All_Elements[i].className==Class_Name)
1260 Result.push(All_Elements[i]);
1261 return Result;
1263 function ShowHide (name)
1265 elements=getElementsByClassName(name);
1266 for(i=0; i<elements.length; i++)
1267 if (elements[i].style.display == "none")
1268 elements[i].style.display = "";
1269 else
1270 elements[i].style.display = "none";
1271 //if (elements[i].style.visibility == "hidden")
1272 // elements[i].style.visibility = "visible";
1273 //else
1274 // elements[i].style.visibility = "hidden";
1276 function filter_by_output(text)
1279 var jjj=0;
1281 elements=getElementsByClassName('command');
1282 for(i=0; i<elements.length; i++) {
1283 subelems = elements[i].getElementsByTagName('pre');
1284 for(j=0; j<subelems.length; j++) {
1285 if (subelems[j].className = 'output') {
1286 var str = new String(subelems[j].nodeValue);
1287 if (jjj != 1) {
1288 alert(str);
1289 jjj=1;
1291 if (str.indexOf(text) >0)
1292 subelems[j].style.display = "none";
1293 else
1294 subelems[j].style.display = "";
1302 JS
1304 %Search_Machines = (
1305 "google" => { "query" => "http://www.google.com/search?q=" ,
1306 "icon" => "$Config{frontend_google_ico}" },
1307 "freebsd" => { "query" => "http://www.freebsd.org/cgi/man.cgi?query=",
1308 "icon" => "$Config{frontend_freebsd_ico}" },
1309 "linux" => { "query" => "http://man.he.net/?topic=",
1310 "icon" => "$Config{frontend_linux_ico}"},
1311 "opennet" => { "query" => "http://www.opennet.ru/search.shtml?words=",
1312 "icon" => "$Config{frontend_opennet_ico}"},
1313 "local" => { "query" => "http://www.freebsd.org/cgi/man.cgi?query=",
1314 "icon" => "$Config{frontend_local_ico}" },
1316 );
1318 %Elements_Visibility = (
1319 "note" => "замечания",
1320 "diff" => "редактор",
1321 "time" => "время",
1322 "ttychange" => "терминал",
1323 "wrong_output wrong_cline wrong_root_output wrong_root_cline"
1324 => "команды с ошибками",
1325 "interrupted_output interrupted_cline interrupted_root_output interrupted_root_cline"
1326 => "прерванные команды",
1327 "tab_completion_output tab_completion_cline"
1328 => "продолжение с помощью tab"
1329 );
1331 @Day_Name = qw/ Воскресенье Понедельник Вторник Среда Четверг Пятница Суббота /;
1332 @Month_Name = qw/ Январь Февраль Март Апрель Май Июнь Июль Август Сентябрь Октябрь Ноябрь Декабрь /;
1333 @Of_Month_Name = qw/ Января Февраля Марта Апреля Мая Июня Июля Августа Сентября Октября Ноября Декабря /;
1339 # Временно удалённый код
1340 # Возможно, он не понадобится уже никогда
1343 sub search_by
1345 my $sm = shift;
1346 my $topic = shift;
1347 $topic =~ s/ /+/;
1349 return "<a href='". $Search_Machines{$sm}->{"query"}."$topic'><img width='16' height='16' src='".
1350 $Search_Machines{$sm}->{"icon"}."' border='0'/></a>";