lilalo

view l3-frontend @ 37:219389279acb

Множество изменений, которые были сделаны в ходе
первой обкатки LiLaLo в реальных условиях.

Добавлена фильтрация и возможность просмотра
смешанного журнала с хоста, без разделения по пользователям
author devi
date Fri Nov 18 17:46:09 2005 +0200 (2005-11-18)
parents cb822611b240
children 466bea239d25
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; # Сколько раз в журнале встречается какая команда
26 sub search_buy;
27 sub make_comment;
28 sub load_command_lines_from_xml;
29 sub load_sessions_from_xml;
30 sub print_command_lines;
31 sub sort_command_lines;
32 sub process_command_lines;
33 sub init_variables;
34 sub main;
35 sub collapse_list($);
37 main();
39 sub main
40 {
41 $| = 1;
43 init_variables();
44 init_config();
46 open_mywi_socket();
47 load_command_lines_from_xml($Config{"backend_datafile"});
48 load_sessions_from_xml($Config{"backend_datafile"});
49 sort_command_lines;
50 process_command_lines;
51 print_command_lines($Config{"output"});
52 close_mywi_socket;
53 }
56 sub search_by
57 {
58 my $sm = shift;
59 my $topic = shift;
60 $topic =~ s/ /+/;
62 return "<a href='". $Search_Machines{$sm}->{"query"}."$topic'><img width='16' height='16' src='".
63 $Search_Machines{$sm}->{"icon"}."' border='0'/></a>";
64 }
66 sub extract_from_cline
67 # Разобрать командную строку $_[1] и возвратить хэш, содержащий
68 # номер первого появление команды в строке:
69 # команда => первая позиция
70 {
71 my $what = $_[0];
72 my $cline = $_[1];
73 my @lists = split /\;/, $cline;
76 my @commands = ();
77 for my $list (@lists) {
78 push @commands, split /\|/, $list;
79 }
81 my %commands;
82 my %args;
83 my $i=0;
84 for my $command (@commands) {
85 $command =~ s@^\s*\S+/@@;
86 $command =~ /\s*(\S+)\s*(.*)/;
87 if ($1 && $1 eq "sudo" ) {
88 $commands{"$1"}=$i++;
89 $command =~ s/\s*sudo\s+//;
90 }
91 $command =~ s@^\s*\S+/@@;
92 $command =~ /\s*(\S+)\s*(.*)/;
93 if ($1 && !defined $commands{"$1"}) {
94 $commands{"$1"}=$i++;
95 };
96 if ($2) {
97 my $args = $2;
98 my @args = split (/\s+/, $args);
99 for my $a (@args) {
100 $args{"$a"}=$i++
101 if !defined $args{"$a"};
102 };
105 }
106 }
108 if ($what eq "commands") {
109 return \%commands;
110 } else {
111 return \%args;
112 }
114 }
116 sub open_mywi_socket
117 {
118 $Mywi_Socket = IO::Socket::INET->new(
119 PeerAddr => $Config{mywi_server},
120 PeerPort => $Config{mywi_port},
121 Proto => "tcp",
122 Type => SOCK_STREAM);
123 }
125 sub close_mywi_socket
126 {
127 close ($Mywi_Socket);
128 }
131 sub mywi_client
132 {
133 my $query = $_[0];
134 my $mywi;
136 open_mywi_socket;
137 if ($Mywi_Socket) {
138 local $| = 1;
139 local $/ = "";
140 print $Mywi_Socket $query."\n";
141 $mywi = <$Mywi_Socket>;
142 $mywi = "" if $mywi =~ /nothing app/;
143 }
144 close_mywi_socket;
145 return $mywi;
146 }
148 sub make_comment
149 {
150 my $cline = $_[0];
151 #my $files = $_[1];
153 my @comments=();
154 my @commands = keys %{extract_from_cline("commands", $cline)};
155 my @args = keys %{extract_from_cline("args", $cline)};
156 return if (!@commands && !@args);
157 #return "commands=".join(" ",@commands)."; files=".join(" ",@files);
159 # Commands
160 for my $command (@commands) {
161 $command =~ s/'//g;
162 $CommandsFDistribution{$command}++;
163 if (!$Commands_Description{$command}) {
164 my $mywi="";
165 $mywi = mywi_client ($command);
166 $mywi = join ("\n", grep(/\([18]\)/, split(/\n/, $mywi)));
167 $mywi =~ s/\s+/ /;
168 if ($mywi !~ /^\s*$/) {
169 $Commands_Description{$command} = $mywi;
170 }
171 else {
172 next;
173 }
174 }
176 push @comments, $Commands_Description{$command};
177 }
178 return join("&#10;\n", @comments);
180 # Files
181 for my $arg (@args) {
182 $arg =~ s/'//g;
183 if (!$Args_Description{$arg}) {
184 my $mywi;
185 $mywi = mywi_client ($arg);
186 $mywi = join ("\n", grep(/\([5]\)/, split(/\n/, $mywi)));
187 $mywi =~ s/\s+/ /;
188 if ($mywi !~ /^\s*$/) {
189 $Args_Description{$arg} = $mywi;
190 }
191 else {
192 next;
193 }
194 }
196 push @comments, $Args_Description{$arg};
197 }
199 }
201 =cut
202 Процедура load_command_lines_from_xml выполняет загрузку разобранного lab-скрипта
203 из XML-документа в переменную @Command_Lines
205 Предупреждение!
206 Процедура не в состоянии обрабатывать XML-документ любой структуры.
207 В действительности файл cache из которого загружаются данные
208 просто напоминает XML с виду.
209 =cut
210 sub load_command_lines_from_xml
211 {
212 my $datafile = $_[0];
214 open (CLASS, $datafile)
215 or die "Can't open file of the class ",$datafile,"\n";
216 local $/;
217 $data = <CLASS>;
218 close(CLASS);
220 for $command ($data =~ m@<command>(.*?)</command>@sg) {
221 my %cl;
222 while ($command =~ m@<([^>]*?)>(.*?)</\1>@sg) {
223 $cl{$1} = $2;
224 }
225 push @Command_Lines, \%cl;
226 }
227 }
229 sub load_sessions_from_xml
230 {
231 my $datafile = $_[0];
233 open (CLASS, $datafile)
234 or die "Can't open file of the class ",$datafile,"\n";
235 local $/;
236 my $data = <CLASS>;
237 close(CLASS);
239 for my $session ($data =~ m@<session>(.*?)</session>@sg) {
240 my %session;
241 while ($session =~ m@<([^>]*?)>(.*?)</\1>@sg) {
242 $session{$1} = $2;
243 }
244 $Sessions{$session{local_session_id}} = \%session;
245 }
246 }
250 sub sort_command_lines
251 {
252 # Sort Command_Lines
253 # Write Command_Lines to Command_Lines_Index
255 my @index;
256 for (my $i=0;$i<=$#Command_Lines;$i++) {
257 $index[$i]=$i;
258 }
260 @Command_Lines_Index = sort {
261 $Command_Lines[$index[$a]]->{"time"} <=> $Command_Lines[$index[$b]]->{"time"}
262 } @index;
264 }
266 sub process_command_lines
267 {
268 for my $i (@Command_Lines_Index) {
270 my $cl = \$Command_Lines[$i];
271 #@{${$cl}->{"new_commands"}} =();
272 #@{${$cl}->{"new_files"}} =();
273 $$cl->{"class"} = "";
275 if ($$cl->{"err"}) {
276 $$cl->{"class"}="wrong";
277 $$cl->{"class"}="interrupted"
278 if ($$cl->{"err"} eq 130);
279 }
280 if (!$$cl->{"euid"}) {
281 $$cl->{"class"}.="_root";
282 }
284 #tab# my @tab_words=split /\s+/, $$cl->{"output"};
285 #tab# my $last_word= $$cl->{"cline"} =~ /(\S*)$/;
286 #tab# $last_word =~ s@.*/@@;
287 #tab# my $this_is_tab=1;
288 #tab#
289 #tab# if ($last_word && @tab_words >2) {
290 #tab# for my $tab_words (@tab_words) {
291 #tab# if ($tab_words !~ /^$last_word/) {
292 #tab# $this_is_tab=0;
293 #tab# last;
294 #tab# }
295 #tab# }
296 #tab# }
297 #tab# $$cl->{"class"}="tab" if $this_is_tab;
300 # if ( !$$cl->{"err"}) {
301 # # Command does not contain mistakes
302 #
303 # my %commands = extract_from_cline("commands", ${$cl}->{"cline"});
304 # my %files = extract_from_cline("files", ${$cl}->{"cline"});
305 #
306 # # Searching for new commands only
307 # for my $command (keys %commands) {
308 # if (!defined $Commands_Stat{$command}) {
309 # push @{$$cl->{new_commands}}, $command;
310 # }
311 # $Commands_Stat{$command}++;
312 # }
313 #
314 # for my $file (keys %files) {
315 # if (!defined $Files_Stat{$file}) {
316 # push @{$$cl->{new_files}}, $file;
317 # }
318 # $Files_Stat{$file}++;
319 # }
320 # }
322 if ($$cl->{cline}=~ m@cat[^#]*#([\^=v])\s*(.*)@) {
323 if ($1 eq "=") {
324 $$cl->{"class"} = "note";
325 $$cl->{"note"} = $$cl->{"output"};
326 $$cl->{"note_title"} = $2;
327 }
328 else {
329 my $j = $i;
330 if ($1 eq "^") {
331 $j--;
332 $j-- while ($j >=0 && (!$Command_Lines[$j] || $Command_Lines[$j]->{tty} ne $$cl->{tty}));
333 }
334 elsif ($1 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}="$2";
339 $Command_Lines[$j]->{note}=$$cl->{output};
340 $$cl=0;
341 }
342 }
343 elsif ($$cl->{cline}=~ /#([\^=v])(.*)/) {
344 if ($1 eq "=") {
345 $$cl->{"class"} = "note";
346 $$cl->{"note"} = $2;
347 }
348 else {
349 my $j=$i;
350 if ($1 eq "^") {
351 $j--;
352 $j-- while ($j >=0 && (!$Command_Lines[$j] || $Command_Lines[$j]->{tty} ne $$cl->{tty}));
353 }
354 elsif ($1 eq "v") {
355 $j++;
356 $j++ while ($j <= @Command_Lines && $Command_Lines[$j]->{tty} ne $$cl->{tty} || !$Command_Lines[$j]);
357 }
358 $Command_Lines[$j]->{note}.="$2\n";
359 $$cl=0;
360 }
361 }
362 }
364 }
367 =cut
368 Процедура print_command_lines выводит HTML-представление
369 разобранного lab-скрипта.
371 Разобранный lab-скрипт должен находиться в массиве @Command_Lines
372 =cut
374 sub print_command_lines
375 {
376 my $output_filename=$_[0];
378 my $course_name = $Config{"course-name"};
379 my $course_code = $Config{"course-code"};
380 my $course_date = $Config{"course-date"};
381 my $course_center = $Config{"course-center"};
382 my $course_trainer = $Config{"course-trainer"};
383 my $course_student = $Config{"course-student"};
386 # Результат выполнения процедуры равен
387 # join("", @Result{header,body,stat,help,about,footer})
388 my %Result;
389 my @toc; # Хранит оглавление
390 my $note_number=0;
392 $Result{"body"} = "<table width='100%'>\n";
394 my $cl;
395 my $last_tty="";
396 my $last_day="";
397 my $in_range=0;
399 my $i=0;
401 COMMAND_LINE:
402 for my $k (@Command_Lines_Index) {
404 my $cl=$Command_Lines[$Command_Lines_Index[$i++]];
406 next unless $cl;
409 if ($Config{filter}) {
410 # Инициализация фильтра
411 my %filter;
412 for (split /&/,$Config{filter}) {
413 my ($var, $val) = split /=/;
414 $filter{$var} = $val;
415 }
417 for my $filter_key (keys %filter) {
418 next COMMAND_LINE unless $Sessions{$cl->{local_session_id}}->{$filter_key} eq $filter{$filter_key};
419 }
421 #if ($filter{user}) {
422 # next COMMAND_LINE unless $Sessions{$cl->{local_session_id}}->{user} eq $filter{user};
423 #}
425 #for my $filter_field (keys %filter) {
426 # next COMMAND_LINE unless $Sessions{$cl->{local_session_id}}->{$filter_field} eq $filter{$filter_field};
427 #}
428 }
430 if ($Config{"from"} && $cl->{"cline"} =~ /$Config{"signature"}\s*$Config{"from"}/) {
431 $in_range=1;
432 next;
433 }
434 if ($Config{"to"} && $cl->{"cline"} =~ /$Config{"signature"}\s*$Config{"to"}/) {
435 $in_range=0;
436 next;
437 }
438 next if ($Config{"from"} && $Config{"to"} && !$in_range)
439 ||
440 ($Config{"skip_empty"} =~ /^y/i && $cl->{"cline"} =~ /^\s*$/ )
441 ||
442 ($Config{"skip_wrong"} =~ /^y/i && $cl->{"err"} != 0)
443 ||
444 ($Config{"skip_interrupted"} =~ /^y/i && $cl->{"err"} == 130);
446 #my @new_commands=@{$cl->{"new_commands"}};
447 #my @new_files=@{$cl->{"new_files"}};
449 if ($cl->{class} eq "note") {
450 my $note = $cl->{note};
451 $note = join ("\n", map ("<p>$_</p>", split (/-\n/, $note)));
452 $note =~ s@(http:[a-zA-Z.0-9/?%-]*)@<a href='$1'>$1</a>@g;
453 $note =~ s@(www\.[a-zA-Z.0-9/?%-]*)@<a href='$1'>$1</a>@g;
454 $Result{"body"} .= "<tr><td colspan='6'>";
455 $Result{"body"} .= "<h4 id='note$note_number'>".$cl->{note_title}."</h4>" if $cl->{note_title};
456 $Result{"body"} .= "".$note."<p/><p/></td></td>";
458 if ($cl->{note_title}) {
459 push @{$toc[@toc]},"<a href='#note$note_number'>".$cl->{note_title}."</a>";
460 $note_number++;
461 }
462 next;
463 }
465 my $cl_class="cline";
466 my $out_class="output";
467 if ($cl->{"class"}) {
468 $cl_class = $cl->{"class"}."_".$cl_class;
469 $out_class = $cl->{"class"}."_".$out_class;
470 }
472 my @new_commands;
473 my @new_files;
474 @new_commands = split (/\s+/, $cl->{"new_commands"}) if defined $cl->{"new_commands"};
475 @new_files = split (/\s+/, $cl->{"new_files"}) if defined $cl->{"new_files"};
477 my $output="";
478 if ($Config{"head_lines"} || $Config{"tail_lines"}) {
479 # Partialy output
480 my @lines = split '\n', $cl->{"output"};
481 # head
482 my $mark=1;
483 for (my $i=0; $i<= $#lines && $i < $Config{"head_lines"}; $i++) {
484 $output .= $lines[$i]."\n";
485 }
486 # tail
487 my $start=$#lines-$Config{"tail_lines"}+1;
488 if ($start < 0) {
489 $start=0;
490 $mark=0;
491 }
492 if ($start < $Config{"head_lines"}) {
493 $start=$Config{"head_lines"};
494 $mark=0;
495 }
496 $output .= $Config{"skip_text"}."\n" if $mark;
497 for (my $i=$start; $i<= $#lines; $i++) {
498 $output .= $lines[$i]."\n";
499 }
500 }
501 else {
502 # Full output
503 $output .= $cl->{"output"};
504 }
505 #$output .= "^C\n" if ($cl->{"err"} eq "130");
507 #
508 ##
509 ## Начинается собственно вывод
510 ##
511 #
513 # <command>
515 my ($sec,$min,$hour,$day,$mon,$year,$wday,$yday,$isdst) = localtime($cl->{time});
516 $Stat{FirstCommand} = $cl->{time} unless $Stat{FirstCommand};
517 $Stat{LastCommand} = 0 unless defined $Stat{LastCommand};
518 $Stat{TotalTime} += $cl->{time} - $Stat{LastCommand}
519 if $cl->{time} - $Stat{LastCommand} < $Config{stat_inactivity_interval};
520 $Stat{LastCommand} = $cl->{time};
521 $Stat{TotalCommands} = 0 unless $Stat{TotalCommands};
522 $Stat{TotalCommands}++;
524 # Добавляем спереди 0 для удобочитаемости
525 $min = "0".$min if $min =~ /^.$/;
526 $hour = "0".$hour if $hour =~ /^.$/;
527 $sec = "0".$sec if $sec =~ /^.$/;
529 $class=$cl->{"out_class"};
530 $class =~ s/output$//;
532 $Stat{ErrorCommands}++
533 if $class =~ /wrong/;
535 $Result{"body"} .= "<tr class='command'>\n";
538 # DAY CHANGE
539 if ( $last_day ne $day) {
540 #$Result{"body"} .= "<td colspan='6'><p></p><h3>День ",$day,"</h4></td></tr><tr>";
541 $Result{"body"} .= "<td colspan='6'><p></p><h3 id='day$day'>".$Day_Name[$wday]."</h4></td></tr><tr>";
542 push @toc, "<a href='#day$day'>".$Day_Name[$wday]."</a>\n";
543 $last_day=$day;
544 }
546 # CONSOLE CHANGE
547 if ( $last_tty ne $cl->{"tty"}) {
548 my $host;
549 #$host = $Sessions{$cl->{local_session_id}}->{user}."@".$Sessions{$cl->{local_session_id}}->{hostname};
550 $Result{"body"} .= "<td colspan='6'><table><tr><td class='ttychange' width='140' align='center'>".$cl->{"tty"}."</td><td>$host</td></tr></table></td></tr><tr>";
551 $last_tty=$cl->{"tty"};
552 }
554 # TIME
555 if ($Config{"show_time"} =~ /^y/i) {
556 $Result{"body"} .= "<td valign='top' class='time' width='$Config{time_width}'><pre>".
557 $hour. ":". $min. ":". $sec.
558 "</td>";
559 } else {
560 $Result{"body"} .= "<td width='0'/>"
561 }
563 # COMMAND
564 $Result{"body"} .= "<td class='script'>\n";
565 $Result{"body"} .= "<pre class='${class}cline'>\n";
566 my $cline = $cl->{"prompt"}.$cl->{"cline"};
567 $cline =~ s/\n//;
569 #$cline .= "(".$Sessions{$cl->{local_session_id}}.")";
571 my $hint = make_comment($cl->{"cline"});
572 $cline = "<div title='$hint'>$cline</div>" if $hint;
573 $Result{"body"} .= $cline;
574 $Result{"body"} .= "</pre>\n";
576 my $last_command = $cl->{"last_command"};
577 if (!(
578 $Config{"suppress_editors"} =~ /^y/i && grep ($_ eq $last_command, @{$Config{"editors"}}) ||
579 $Config{"suppress_pagers"} =~ /^y/i && grep ($_ eq $last_command, @{$Config{"pagers"}}) ||
580 $Config{"suppress_terminal"}=~ /^y/i && grep ($_ eq $last_command, @{$Config{"terminal"}})
581 )) {
583 $Result{"body"} .= "<pre class='".$cl->{out_class}."'>";
584 $Result{"body"} .= $output;
585 $Result{"body"} .= "</pre>\n";
586 }
588 # DIFF
589 if ( $Config{"show_diffs"} =~ /^y/i && $cl->{"diff"}) {
590 $Result{"body"} .= "<table><tr><td width='5'/><td class='diff'><pre>";
591 $Result{"body"} .= $cl->{"diff"};
592 $Result{"body"} .= "</pre></td></tr></table>";
593 }
595 #NOTES
596 if ( $Config{"show_notes"} =~ /^y/i && $cl->{"note"}) {
597 my $note=$cl->{"note"};
598 $note =~ s/\n/<br\/>\n/msg;
599 $note =~ s@(http:[a-zA-Z.0-9/?%-]*)@<a href='$1'>$1</a>@g;
600 $note =~ s@(www\.[a-zA-Z.0-9/?%-]*)@<a href='$1'>$1</a>@g;
601 # Ширину пока не используем
602 # $Result{"body"} .= "<table width='$Config{note_width}' class='note'>";
603 $Result{"body"} .= "<table class='note'>";
604 $Result{"body"} .= "<tr><td class='note_title'>".$cl->{note_title}."</td></tr>" if $cl->{note_title};
605 $Result{"body"} .= "<tr><td width='100%' class='note_text'>".$note."</td></tr>";
606 $Result{"body"} .= "</table>\n";
607 }
609 # COMMENT
610 if ( $Config{"show_comments"} =~ /^y/i) {
611 my $comment = make_comment($cl->{"cline"});
612 if ($comment) {
613 $Result{"body"} .= "<table width='$Config{comment_width}'>".
614 "<tr><td width='5'/><td>";
615 $Result{"body"} .= "<table class='note' width='100%'>";
616 $Result{"body"} .= $comment;
617 $Result{"body"} .= "</table>\n";
618 $Result{"body"} .= "</td></tr></table>";
619 }
620 }
622 # Вывод очередной команды окончен
623 $Result{"body"} .= "</td>\n";
624 $Result{"body"} .= "</tr>\n";
625 }
627 $Result{"body"} .= "</table>\n";
629 #$Result{"stat"} = "<hr/>";
631 %StatNames = (
632 FirstCommand => "Время первой команды журнала",
633 LastCommand => "Время последней команды журнала",
634 TotalCommands => "Количество командных строк в журнале",
635 ErrorsPercentage => "Процент команд с ненулевым кодом завершения, %",
636 TotalTime => "Суммарное время работы с терминалом <sup><font size='-2'>*</font></sup>, час",
637 CommandsPerTime => "Количество командных строк в единицу времени, команда/мин",
638 CommandsFrequency => "Частота использования команд",
639 RareCommands => "Частота использования этих команд < 0.5%",
640 );
641 @StatOrder = (
642 FirstCommand,
643 LastCommand,
644 TotalCommands,
645 ErrorsPercentage,
646 TotalTime,
647 CommandsPerTime,
648 CommandsFrequency,
649 RareCommands,
650 );
652 # Подготовка статистики к выводу
653 # Некоторые значения пересчитываются!
654 # Дальше их лучше уже не использовать!!!
656 my %CommandsFrequency = %CommandsFDistribution;
658 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($Stat{FirstCommand});
659 $Stat{FirstCommand} = sprintf "%02i:%02i:%02i %04i-%2i-%2i", $hour, $min, $sec, $year+1900, $mon+1, $mday;
660 ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($Stat{LastCommand});
661 $Stat{LastCommand} = sprintf "%02i:%02i:%02i %04i-%2i-%2i", $hour, $min, $sec, $year+1900, $mon+1, $mday;
662 $Stat{ErrorsPercentage} = sprintf "%5.2f", $Stat{ErrorCommands}*100/$Stat{TotalCommands}
663 if $Stat{TotalCommands};
664 $Stat{CommandsPerTime} = sprintf "%5.2f", $Stat{TotalCommands}*60/$Stat{TotalTime}
665 if $Stat{TotalTime};
666 $Stat{TotalTime} = sprintf "%5.2f", $Stat{TotalTime}/60/60;
668 my $total_commands=0;
669 for $command (keys %CommandsFrequency){
670 $total_commands += $CommandsFrequency{$command};
671 }
672 if ($total_commands) {
673 for $command (reverse sort {$CommandsFrequency{$a} <=> $CommandsFrequency{$b}} keys %CommandsFrequency){
674 my $command_html;
675 my $percentage = sprintf "%5.2f",$CommandsFrequency{$command}*100/$total_commands;
676 if ($percentage < 0.5) {
677 my $hint = make_comment($command);
678 $command_html = "$command";
679 $command_html = "<span title='$hint' class='hint'>$command_html</span>" if $hint;
680 my $command_html = "<tt>$command_html</tt>";
681 $Stat{RareCommands} .= $command_html."<sub><font size='-2'>".$CommandsFrequency{$command}."</font></sub> , ";
682 }
683 else {
684 my $hint = make_comment($command);
685 $command_html = "$command";
686 $command_html = "<span title='$hint' class='hint'>$command_html</span>" if $hint;
687 my $command_html = "<tt>$command_html</tt>";
688 $percentage = sprintf "%5.2f",$percentage;
689 $Stat{CommandsFrequency} .= "<tr><td>".$command_html."</td><td>".$CommandsFrequency{$command}."</td>".
690 "<td>|".("="x int($CommandsFrequency{$command}*100/$total_commands))."| $percentage%</td></tr>";
691 }
692 }
693 $Stat{CommandsFrequency} = "<table>".$Stat{CommandsFrequency}."</table>";
694 $Stat{RareCommands} =~ s/, $// if $Stat{RareCommands};
695 }
697 $Result{"stat"} .= "<h2 id='stat'>Статистика</h2>";
698 $Result{"stat"} .= "<table>";
699 for my $stat (@StatOrder) {
700 $Result{"stat"} .= "<tr valign='top'><td width='300'>".$StatNames{"$stat"}."</td><td>".$Stat{"$stat"}."</td></tr>"
701 if $Stat{"$stat"};
702 }
704 $Result{"stat"} .= "</table>";
705 $Result{"stat"} .= "<font size='-2'>____<br/>*) Интервалы неактивности длительностью ".($Config{stat_inactivity_interval}/60)." минут и более не учитываются</font></br>";
707 #$Result{"help"} .= "<hr/>";
708 $Result{"help"} .= "<h2 id='help'>Справка</h2>";
709 $Result{"help"} .= "$Html_Help<br/>";
710 #$Result{"about"} .= "<hr/>";
711 $Result{"about"} .= "<h2 id='about'>О программе</h2>";
712 $Result{"about"} .= "$Html_About";
713 $Result{"footer"} .= "</body>\n";
714 $Result{"footer"} .= "</html>\n";
716 $Result{"title"} = "Журнал лабораторных работ";
717 $Result{"title"}.= " -- ".$course_student if $course_student;
718 if ($course_date) {
719 $Result{"title"}.= " -- ".$course_date;
720 $Result{"title"}.= "/".$course_code if $course_code;
721 }
722 else {
723 $Result{"title"}.= " -- ".$course_code if $course_code;
724 }
726 # Заголовок генерируется позже всего
727 # Тогда, когда известно уже, что должно быть написано в
728 # оглавлении
729 $Result{"header"} = <<HEADER;
730 <html>
731 <head>
732 <meta content='text/html; charset=utf-8' http-equiv='Content-Type' />
733 <link rel='stylesheet' href='$Config{frontend_css}' type='text/css'/>
734 <title>$Result{title}</title>
735 </head>
736 <body>
737 <script>
738 $Html_JavaScript
739 </script>
740 <h1>Журнал лабораторных работ</h1>
742 HEADER
743 $Result{"header"} .= "<p>" if $course_student || $course_trainer || $course_name || $course_code || $course_date || $course_center;
744 $Result{"header"} .= "Выполнил $course_student<br/>" if $course_student;
745 $Result{"header"} .= "Проверил $course_trainer <br/>" if $course_trainer;
746 $Result{"header"} .= "Курс " if $course_name || $course_code || $course_date;
747 $Result{"header"} .= "$course_name " if $course_name;
748 $Result{"header"} .= "($course_code)" if $course_code;
749 $Result{"header"} .= ", $course_date<br/>" if $course_date;
750 $Result{"header"} .= "Учебный центр $course_center <br/>" if $course_center;
751 $Result{"header"} .= "</p>" if $course_student || $course_trainer || $course_name || $course_code || $course_date || $course_center;
753 my $toc = collapse_list (\@toc);
754 $Result{"header"} .= <<HEADER;
755 <ul>
756 <li><a href='#log'>Журнал</a></li>
757 <ul>$toc</ul>
758 <li><a href='#stat'>Статистика</a></li>
759 <li><a href='#help'>Справка</a></li>
760 <li><a href='#about'>О программе</a></li>
761 </ul>
763 <h2 id="log">Журнал</h2>
764 HEADER
765 $Result{"header"} .= "<table id='visibility_form' class='visibility_form'><tr><td><form>\n";
766 for my $element (keys %Elements_Visibility)
767 {
768 my @e = split /\s+/, $element;
769 my $showhide = join "", map { "ShowHide('$_');" } @e ;
770 $Result{"header"} .= "<input type='checkbox' name='$e[0]' onclick=\"$showhide\" checked>".
771 $Elements_Visibility{$element}.
772 "</input><br>\n";
773 }
775 $Result{"header"} .= "</form></td></tr></table>\n";
777 if ($output_filename eq "-") {
778 print $Result{"header"}, $Result{"body"}, $Result{"stat"}, $Result{"help"}, $Result{"about"}, $Result{"footer"};
779 }
780 else {
781 open(OUT, ">", $output_filename)
782 or die "Can't open $output_filename for writing\n";
783 print OUT $Result{"header"}, $Result{"body"}, $Result{"stat"}, $Result{"help"}, $Result{"about"}, $Result{"footer"};
784 close(OUT);
785 }
786 }
790 sub collapse_list($)
791 {
792 my $res = "";
793 for my $elem (@{$_[0]}) {
794 if (ref $elem eq "ARRAY") {
795 $res .= "<ul>".collapse_list($elem)."</ul>";
796 }
797 else
798 {
799 $res .= "<li>".$elem."</li>";
800 }
801 }
802 return $res;
803 }
808 sub init_variables
809 {
810 $Html_Help = <<HELP;
811 Для того чтобы использовать LiLaLo, не нужно знать ничего особенного:
812 всё происходит само собой.
813 Однако, чтобы ведение и последующее использование журналов
814 было как можно более эффективным, желательно иметь в виду следующее:
815 <ul>
816 <li><p>
817 В журнал автоматически попадают все команды, данные в любом терминале системы.
818 </p></li>
819 <li><p>
820 Для того чтобы убедиться, что журнал на текущем терминале ведётся,
821 и команды записываются, дайте команду w.
822 В поле WHAT, соответствующем текущему терминалу,
823 должна быть указана программа script.
824 </p></li>
825 <li><p>
826 Если код завершения команды равен нулю,
827 команда была выполнена без ошибок.
828 Команды, код завершения которых отличен от нуля, выделяются цветом.
829 <table>
830 <tr class='command'>
831 <td class='script'>
832 <pre class='wrong_cline'>
833 \$ l s-l</pre>
834 <pre class='wrong_output'>bash: l: command not found
835 </pre>
836 </td>
837 </tr>
838 </table>
839 <br/>
840 </p></li>
841 <li><p>
842 Команды, ход выполнения которых был прерван пользователем, выделяются цветом.
843 <table>
844 <tr class='command'>
845 <td class='script'>
846 <pre class='interrupted_cline'>
847 \$ find / -name abc</pre>
848 <pre class='interrupted_output'>find: /home/devi-orig/.gnome2: Keine Berechtigung
849 find: /home/devi-orig/.gnome2_private: Keine Berechtigung
850 find: /home/devi-orig/.nautilus/metafiles: Keine Berechtigung
851 find: /home/devi-orig/.metacity: Keine Berechtigung
852 find: /home/devi-orig/.inkscape: Keine Berechtigung
853 ^C
854 </pre>
855 </td>
856 </tr>
857 </table>
858 <br/>
859 </p></li>
860 <li><p>
861 Команды, выполненные с привилегиями суперпользователя,
862 выделяются слева красной чертой.
863 <table>
864 <tr class='command'>
865 <td class='script'>
866 <pre class='_root_cline'>
867 # id</pre>
868 <pre class='_root_output'>
869 uid=0(root) gid=0(root) Gruppen=0(root)
870 </pre>
871 </td>
872 </tr>
873 </table>
874 <br/>
875 </p></li>
876 <li><p>
877 Изменения, внесённые в текстовый файл с помощью редактора,
878 запоминаются и показываются в журнале в формате ed.
879 Строки, начинающиеся символом "&lt;", удалены, а строки,
880 начинающиеся символом "&gt;" -- добавлены.
881 <table>
882 <tr class='command'>
883 <td class='script'>
884 <pre class='cline'>
885 \$ vi ~/.bashrc</pre>
886 <table><tr><td width='5'/><td class='diff'><pre>2a3,5
887 &gt; if [ -f /usr/local/etc/bash_completion ]; then
888 &gt; . /usr/local/etc/bash_completion
889 &gt; fi
890 </pre></td></tr></table></td>
891 </tr>
892 </table>
893 <br/>
894 </p></li>
895 <li><p>
896 Для того чтобы получить краткую справочную информацию о команде,
897 нужно подвести к ней мышь. Во всплывающей подсказке появится краткое
898 описание команды.
899 </p></li>
900 <li><p>
901 Время ввода команды, показанное в журнале, соответствует времени
902 <i>начала ввода командной строки</i>, которое равно тому моменту,
903 когда на терминале появилось приглашение интерпретатора
904 </p></li>
905 <li><p>
906 Имя терминала, на котором была введена команда, показано в специальном блоке.
907 Этот блок показывается только в том случае, если терминал
908 текущей команды отличается от терминала предыдущей.
909 </p></li>
910 <li><p>
911 Вывод не интересующих вас в настоящий момент элементов журнала,
912 таких как время, имя терминала и других, можно отключить.
913 Для этого нужно воспользоваться <a href='#visibility_form'>формой управления журналом</a>
914 вверху страницы.
915 </p></li>
916 <li><p>
917 Небольшие комментарии к командам можно вставлять прямо из командной строки.
918 Комментарий вводится прямо в командную строку, после символов #^ или #v.
919 Символы ^ и v показывают направление выбора команды, к которой относится комментарий:
920 ^ - к предыдущей, v - к следующей.
921 Например, если в командной строке было введено:
922 <pre class='cline'>
923 \$ whoami
924 </pre>
925 <pre class='output'>
926 user
927 </pre>
928 <pre class='cline'>
929 \$ #^ Интересно, кто я?
930 </pre>
931 в журнале это будет выглядеть так:
933 <pre class='cline'>
934 \$ whoami
935 </pre>
936 <pre class='output'>
937 user
938 </pre>
939 <table class='note'><tr><td width='100%' class='note_text'>
940 <tr> <td> Интересно, кто я?<br/> </td></tr></table>
941 </p></li>
942 <li><p>
943 Если комментарий содержит несколько строк,
944 его можно вставить в журнал следующим образом:
945 <pre class='cline'>
946 \$ whoami
947 </pre>
948 <pre class='output'>
949 user
950 </pre>
951 <pre class='cline'>
952 \$ cat > /dev/null #^ Интересно, кто я?
953 </pre>
954 <pre class='output'>
955 Программа whoami выводит имя пользователя, под которым
956 мы зарегистрировались в системе.
957 -
958 Она не может ответить на вопрос о нашем назначении
959 в этом мире.
960 </pre>
961 В журнале это будет выглядеть так:
962 <table>
963 <tr class='command'>
964 <td class='script'>
965 <pre class='cline'>
966 \$ whoami</pre>
967 <pre class='output'>user
968 </pre>
969 <table class='note'><tr><td class='note_title'>Интересно, кто я?</td></tr><tr><td width='100%' class='note_text'>
970 Программа whoami выводит имя пользователя, под которым<br/>
971 мы зарегистрировались в системе.<br/>
972 <br/>
973 Она не может ответить на вопрос о нашем назначении<br/>
974 в этом мире.<br/>
975 </td></tr></table>
976 </td>
977 </tr>
978 </table>
979 Для разделения нескольких абзацев между собой
980 используйте символ "-", один в строке.
981 <br/>
982 </p></li>
983 <li><p>
984 Комментарии, не относящиеся непосредственно ни к какой из команд,
985 добавляются точно таким же способом, только вместо симолов #^ или #v
986 нужно использовать символы #=
987 </p></li>
988 </ul>
989 HELP
991 $Html_About = <<ABOUT;
992 <p>
993 LiLaLo (L3) расшифровывается как Live Lab Log.<br/>
994 Программа разработана для повышения эффективности обучения Unix/Linux-системам.<br/>
995 (c) Игорь Чубин, 2004-2005<br/>
996 </p>
997 ABOUT
998 $Html_About.='$Id$ </p>';
1000 $Html_JavaScript = <<JS;
1001 function getElementsByClassName(Class_Name)
1003 var Result=new Array();
1004 var All_Elements=document.all || document.getElementsByTagName('*');
1005 for (i=0; i<All_Elements.length; i++)
1006 if (All_Elements[i].className==Class_Name)
1007 Result.push(All_Elements[i]);
1008 return Result;
1010 function ShowHide (name)
1012 elements=getElementsByClassName(name);
1013 for(i=0; i<elements.length; i++)
1014 if (elements[i].style.display == "none")
1015 elements[i].style.display = "";
1016 else
1017 elements[i].style.display = "none";
1018 //if (elements[i].style.visibility == "hidden")
1019 // elements[i].style.visibility = "visible";
1020 //else
1021 // elements[i].style.visibility = "hidden";
1023 function filter_by_output(text)
1026 var jjj=0;
1028 elements=getElementsByClassName('command');
1029 for(i=0; i<elements.length; i++) {
1030 subelems = elements[i].getElementsByTagName('pre');
1031 for(j=0; j<subelems.length; j++) {
1032 if (subelems[j].className = 'output') {
1033 var str = new String(subelems[j].nodeValue);
1034 if (jjj != 1) {
1035 alert(str);
1036 jjj=1;
1038 if (str.indexOf(text) >0)
1039 subelems[j].style.display = "none";
1040 else
1041 subelems[j].style.display = "";
1049 JS
1051 %Search_Machines = (
1052 "google" => { "query" => "http://www.google.com/search?q=" ,
1053 "icon" => "$Config{frontend_google_ico}" },
1054 "freebsd" => { "query" => "http://www.freebsd.org/cgi/man.cgi?query=",
1055 "icon" => "$Config{frontend_freebsd_ico}" },
1056 "linux" => { "query" => "http://man.he.net/?topic=",
1057 "icon" => "$Config{frontend_linux_ico}"},
1058 "opennet" => { "query" => "http://www.opennet.ru/search.shtml?words=",
1059 "icon" => "$Config{frontend_opennet_ico}"},
1060 "local" => { "query" => "http://www.freebsd.org/cgi/man.cgi?query=",
1061 "icon" => "$Config{frontend_local_ico}" },
1063 );
1065 %Elements_Visibility = (
1066 "note" => "замечания",
1067 "diff" => "редактор",
1068 "time" => "время",
1069 "ttychange" => "терминал",
1070 "wrong_output wrong_cline wrong_root_output wrong_root_cline"
1071 => "команды с ошибками",
1072 "interrupted_output interrupted_cline interrupted_root_output interrupted_root_cline"
1073 => "прерванные команды",
1074 "tab_completion_output tab_completion_cline"
1075 => "продолжение с помощью tab"
1076 );
1078 @Day_Name = qw/ Воскресенье Понедельник Вторник Среда Четверг Пятница Суббота /;
1079 @Month_Name = qw/ Январь Февраль Март Апрель Май Июнь Июль Август Сентябрь Октябрь Ноябрь Декабрь /;
1080 @Of_Month_Name = qw/ Января Февраля Марта Апреля Мая Июня Июля Августа Сентября Октября Ноября Декабря /;