lilalo

view l3-frontend @ 84:2cb912bff2ea

* В журнале выводится имя курса, а не только его код
* Исправлена ошибка с фильтром при чтении журнала из XML-репозитория
Теперь всё ок
author devi
date Sat Feb 25 08:02:25 2006 +0200 (2006-02-25)
parents bdc1f02d3f87
children c70be67ed3d4
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;
14 our %filter;
16 our %Files;
18 # vvv Инициализация переменных выполняется процедурой init_variables
19 our @Day_Name;
20 our @Month_Name;
21 our @Of_Month_Name;
22 our %Search_Machines;
23 our %Elements_Visibility;
24 # ^^^
26 our %Stat;
27 our %CommandsFDistribution; # Сколько раз в журнале встречается какая команда
28 our $table_number=1;
30 my %mywi_cache_for; # Кэш для экономии обращений к mywi
32 sub make_comment;
33 sub make_new_entries_table;
34 sub load_command_lines_from_xml;
35 sub load_sessions_from_xml;
36 sub sort_command_lines;
37 sub process_command_lines;
38 sub init_variables;
39 sub main;
40 sub collapse_list($);
42 sub print_all;
43 sub print_command_lines;
44 sub print_files;
45 sub print_stat;
46 sub print_header;
47 sub print_footer;
49 main();
51 sub main
52 {
53 $| = 1;
55 init_variables();
56 init_config();
57 $Config{frontend_ico_path}=$Config{frontend_css};
58 $Config{frontend_ico_path}=~s@/[^/]*$@@;
60 open_mywi_socket();
61 load_command_lines_from_xml($Config{"backend_datafile"});
62 load_sessions_from_xml($Config{"backend_datafile"});
63 sort_command_lines;
64 process_command_lines;
65 print_all($Config{"output"});
66 close_mywi_socket;
67 }
69 # extract_from_cline
71 # In: $what = commands | args
72 # Out: return ссылка на хэш, содержащий результаты разбора
73 # команда => позиция
75 # Разобрать командную строку $_[1] и возвратить хэш, содержащий
76 # номер первого появление команды в строке:
77 # команда => первая позиция
78 sub extract_from_cline
79 {
80 my $what = $_[0];
81 my $cline = $_[1];
82 my @lists = split /\;/, $cline;
85 my @command_lines = ();
86 for my $command_list (@lists) {
87 push(@command_lines, split(/\|/, $command_list));
88 }
90 my %position_of_command;
91 my %position_of_arg;
92 my $i=0;
93 for my $command_line (@command_lines) {
94 $command_line =~ s@^\s*@@;
95 $command_line =~ /\s*(\S+)\s*(.*)/;
96 if ($1 && $1 eq "sudo" ) {
97 $position_of_command{"$1"}=$i++;
98 $command_line =~ s/\s*sudo\s+//;
99 }
100 if ($command_line !~ m@^\s*\S*/etc/@) {
101 $command_line =~ s@^\s*\S+/@@;
102 }
104 $command_line =~ /\s*(\S+)\s*(.*)/;
105 my $command = $1;
106 my $args = $2;
107 if ($command && !defined $position_of_command{"$command"}) {
108 $position_of_command{"$command"}=$i++;
109 };
110 if ($args) {
111 my @args = split (/\s+/, $args);
112 for my $a (@args) {
113 $position_of_arg{"$a"}=$i++
114 if !defined $position_of_arg{"$a"};
115 };
116 }
117 }
119 if ($what eq "commands") {
120 return \%position_of_command;
121 } else {
122 return \%position_of_arg;
123 }
125 }
130 #
131 # Подпрограммы для работы с mywi
132 #
134 sub open_mywi_socket
135 {
136 $Mywi_Socket = IO::Socket::INET->new(
137 PeerAddr => $Config{mywi_server},
138 PeerPort => $Config{mywi_port},
139 Proto => "tcp",
140 Type => SOCK_STREAM);
141 }
143 sub close_mywi_socket
144 {
145 close ($Mywi_Socket) if $Mywi_Socket ;
146 }
149 sub mywi_client
150 {
151 my $query = $_[0];
152 my $mywi;
154 open_mywi_socket;
155 if ($Mywi_Socket) {
156 local $| = 1;
157 local $/ = "";
158 print $Mywi_Socket $query."\n";
159 $mywi = <$Mywi_Socket>;
160 $mywi = "" if $mywi =~ /nothing app/;
161 }
162 close_mywi_socket;
163 return $mywi;
164 }
166 sub make_comment
167 {
168 my $cline = $_[0];
169 #my $files = $_[1];
171 my @comments;
172 my @commands = keys %{extract_from_cline("commands", $cline)};
173 my @args = keys %{extract_from_cline("args", $cline)};
174 return if (!@commands && !@args);
175 #return "commands=".join(" ",@commands)."; files=".join(" ",@files);
177 # Commands
178 for my $command (@commands) {
179 $command =~ s/'//g;
180 $CommandsFDistribution{$command}++;
181 if (!$Commands_Description{$command}) {
182 $mywi_cache_for{$command} ||= mywi_client ($command) || "";
183 my $mywi = join ("\n", grep(/\([18]|sh|script\)/, split(/\n/, $mywi_cache_for{$command})));
184 $mywi =~ s/\s+/ /;
185 if ($mywi !~ /^\s*$/) {
186 $Commands_Description{$command} = $mywi;
187 }
188 else {
189 next;
190 }
191 }
193 push @comments, $Commands_Description{$command};
194 }
195 return join("&#10;\n", @comments);
197 # Files
198 for my $arg (@args) {
199 $arg =~ s/'//g;
200 if (!$Args_Description{$arg}) {
201 my $mywi;
202 $mywi = mywi_client ($arg);
203 $mywi = join ("\n", grep(/\([5]\)/, split(/\n/, $mywi)));
204 $mywi =~ s/\s+/ /;
205 if ($mywi !~ /^\s*$/) {
206 $Args_Description{$arg} = $mywi;
207 }
208 else {
209 next;
210 }
211 }
213 push @comments, $Args_Description{$arg};
214 }
216 }
218 =cut
219 Процедура load_command_lines_from_xml выполняет загрузку разобранного lab-скрипта
220 из XML-документа в переменную @Command_Lines
222 # In: $datafile имя файла
223 # Out: @CommandLines загруженные командные строки
225 Предупреждение!
226 Процедура не в состоянии обрабатывать XML-документ любой структуры.
227 В действительности файл cache из которого загружаются данные
228 просто напоминает XML с виду.
229 =cut
230 sub load_command_lines_from_xml
231 {
232 my $datafile = $_[0];
234 open (CLASS, $datafile)
235 or die "Can't open file with xml lablog ",$datafile,"\n";
236 local $/;
237 $data = <CLASS>;
238 close(CLASS);
240 for $command ($data =~ m@<command>(.*?)</command>@sg) {
241 my %cl;
242 while ($command =~ m@<([^>]*?)>(.*?)</\1>@sg) {
243 $cl{$1} = $2;
244 }
245 push @Command_Lines, \%cl;
246 }
247 }
249 sub load_sessions_from_xml
250 {
251 my $datafile = $_[0];
253 open (CLASS, $datafile)
254 or die "Can't open file with xml lablog ",$datafile,"\n";
255 local $/;
256 my $data = <CLASS>;
257 close(CLASS);
259 my $i=0;
260 for my $session ($data =~ m@<session>(.*?)</session>@msg) {
261 my %session_hash;
262 while ($session =~ m@<([^>]*?)>(.*?)</\1>@sg) {
263 $session_hash{$1} = $2;
264 }
265 $Sessions{$session_hash{local_session_id}} = \%session_hash;
266 }
267 }
270 # sort_command_lines
271 # In: @Command_Lines
272 # Out: @Command_Lies_Index
274 sub sort_command_lines
275 {
277 my @index;
278 for (my $i=0;$i<=$#Command_Lines;$i++) {
279 $index[$i]=$i;
280 }
282 @Command_Lines_Index = sort {
283 $Command_Lines[$index[$a]]->{"time"} <=> $Command_Lines[$index[$b]]->{"time"}
284 } @index;
286 }
288 ##################
289 # process_command_lines
290 #
291 # Обрабатываются командные строки @Command_Lines
292 # Для каждой строки определяется:
293 # class класс
294 # note комментарий
295 #
296 # In: @Command_Lines_Index
297 # In-Out: @Command_Lines
299 sub process_command_lines
300 {
301 for my $i (@Command_Lines_Index) {
302 my $cl = \$Command_Lines[$i];
304 next if !$cl;
306 $$cl->{id} = $$cl->{"time"};
308 $$cl->{err} ||=0;
310 # Класс команды
312 $$cl->{"class"} = $$cl->{"err"} eq 130 ? "interrupted"
313 : $$cl->{"err"} eq 127 ? "mistyped"
314 : $$cl->{"err"} ? "wrong"
315 : "normal";
317 if ($$cl->{"cline"} &&
318 $$cl->{"cline"} =~ /[^|`]\s*sudo/
319 || $$cl->{"uid"} eq 0) {
320 $$cl->{"class"}.="_root";
321 }
324 #Обработка пометок
325 # Если несколько пометок (notes) идут подряд,
326 # они все объединяются
328 if ($$cl->{cline} =~ /l3shot/) {
329 if ($$cl->{output} =~ m@Screenshot is written to.*/(.*)\.xwd@) {
330 $$cl->{screenshot}="$1";
331 }
332 }
334 if ($$cl->{cline}=~ m@cat[^#]*#([\^=v])\s*(.*)@) {
336 my $note_operator = $1;
337 my $note_title = $2;
339 if ($note_operator eq "=") {
340 $$cl->{"class"} = "note";
341 $$cl->{"note"} = $$cl->{"output"};
342 $$cl->{"note_title"} = $2;
343 }
344 else {
345 my $j = $i;
346 if ($note_operator eq "^") {
347 $j--;
348 $j-- while ($j >=0 && (!$Command_Lines[$j] || $Command_Lines[$j]->{tty} ne $$cl->{tty}));
349 }
350 elsif ($note_operator eq "v") {
351 $j++;
352 $j++ while ($j <= @Command_Lines && (!$Command_Lines[$j] || $Command_Lines[$j]->{tty} ne $$cl->{tty}));
353 }
354 $Command_Lines[$j]->{note_title}=$note_title;
355 $Command_Lines[$j]->{note}.=$$cl->{output};
356 $$cl=0;
357 }
358 }
359 elsif ($$cl->{cline}=~ /#([\^=v])(.*)/) {
361 my $note_operator = $1;
362 my $note_text = $2;
364 if ($note_operator eq "=") {
365 $$cl->{"class"} = "note";
366 $$cl->{"note"} = $note_text;
367 }
368 else {
369 my $j=$i;
370 if ($note_operator eq "^") {
371 $j--;
372 $j-- while ($j >=0 && (!$Command_Lines[$j] || $Command_Lines[$j]->{tty} ne $$cl->{tty}));
373 }
374 elsif ($note_operator eq "v") {
375 $j++;
376 $j++ while ($j <= @Command_Lines && $Command_Lines[$j]->{tty} ne $$cl->{tty} || !$Command_Lines[$j]);
377 }
378 $Command_Lines[$j]->{note}.="$note_text\n";
379 $$cl=0;
380 }
381 }
382 }
384 }
387 =cut
388 Процедура print_command_lines выводит HTML-представление
389 разобранного lab-скрипта.
391 Разобранный lab-скрипт должен находиться в массиве @Command_Lines
392 =cut
394 sub print_command_lines
395 {
397 my @toc; # Оглавление
398 my $note_number=0;
400 my $result = q();
401 my $this_day_resut = q();
403 my $cl;
404 my $last_tty="";
405 my $last_session="";
406 my $last_day=q();
407 my $last_wday=q();
408 my $in_range=0;
410 my $current_command=0;
412 my @known_commands;
415 if ($Config{filter}) {
416 # Инициализация фильтра
417 for (split /&/,$Config{filter}) {
418 my ($var, $val) = split /=/;
419 $filter{$var} = $val || "";
420 }
421 }
423 #$result = "Filter=".$Config{filter}."\n";
425 $Stat{LastCommand} ||= 0;
426 $Stat{TotalCommands} ||= 0;
427 $Stat{ErrorCommands} ||= 0;
428 $Stat{MistypedCommands} ||= 0;
430 my %new_entries_of = (
431 "1 1" => "программы пользователя",
432 "2 8" => "программы администратора",
433 "3 sh" => "команды интерпретатора",
434 "4 script"=> "скрипты",
435 );
437 COMMAND_LINE:
438 for my $k (@Command_Lines_Index) {
440 my $cl=$Command_Lines[$Command_Lines_Index[$current_command++]];
441 next unless $cl;
443 # Пропускаем команды, с одинаковым временем
444 # Это не совсем правильно.
445 # Возможно, что это команды, набираемые с помощью <completion>
446 # или запомненные с помощью <ctrl-c>
448 next if $Stat{LastCommand} == $cl->{time};
450 # Пропускаем строки, которые противоречат фильтру
451 # Если у нас недостаточно информации о том, подходит строка под фильтр или нет,
452 # мы её выводим
454 #$result .= "before<br/>";
455 for my $filter_key (keys %filter) {
456 #$result .= "undefined local session id<br/>\n" if !defined($cl->{local_session_id});
457 #$result .= "undefined filter key $filter_key <br/>\n" if !defined($Sessions{$cl->{local_session_id}}->{$filter_key});
458 #$result .= $Sessions{$cl->{local_session_id}}->{$filter_key}." != ".$filter{$filter_key};
459 next COMMAND_LINE
460 if defined($cl->{local_session_id})
461 && defined($Sessions{$cl->{local_session_id}}->{$filter_key})
462 && $Sessions{$cl->{local_session_id}}->{$filter_key} ne $filter{$filter_key};
463 }
465 # Набираем статистику
466 # Хэш %Stat
468 $Stat{FirstCommand} = $cl->{time} unless $Stat{FirstCommand};
469 if ($cl->{time} - $Stat{LastCommand} < $Config{stat_inactivity_interval}) {
470 $Stat{TotalTime} += $cl->{time} - $Stat{LastCommand}
471 }
472 my $seconds_since_last_command = $cl->{time} - $Stat{LastCommand};
473 $Stat{LastCommand} = $cl->{time};
474 $Stat{TotalCommands}++;
477 # Пропускаем строки, выходящие за границу "signature",
478 # при условии, что границы указаны
479 # Пропускаем неправильные/прерванные/другие команды
480 if ($Config{"from"} && $cl->{"cline"} =~ /$Config{"signature"}\s*$Config{"from"}/) {
481 $in_range=1;
482 next;
483 }
484 if ($Config{"to"} && $cl->{"cline"} =~ /$Config{"signature"}\s*$Config{"to"}/) {
485 $in_range=0;
486 next;
487 }
488 next if ($Config{"from"} && $Config{"to"} && !$in_range)
489 || ($Config{"skip_empty"} =~ /^y/i && $cl->{"cline"} =~ /^\s*$/ )
490 || ($Config{"skip_wrong"} =~ /^y/i && $cl->{"err"} != 0)
491 || ($Config{"skip_interrupted"} =~ /^y/i && $cl->{"err"} == 130);
493 if ($cl->{class} eq "note") {
494 my $note = $cl->{note};
495 $note = join ("\n", map ("<p>$_</p>", split (/-\n/, $note)));
496 $note =~ s@(http:[a-zA-Z.0-9/?\_%-]*)@<a href='$1'>$1</a>@g;
497 $note =~ s@(www\.[a-zA-Z.0-9/?\_%-]*)@<a href='$1'>$1</a>@g;
498 $this_day_result .= "<tr><td colspan='6'>"
499 . "<h4 id='note$note_number'>".$cl->{note_title}."</h4>" if $cl->{note_title}
500 . "".$note."<p/><p/></td></tr>";
502 if ($cl->{note_title}) {
503 push @{$toc[@toc]},"<a href='#note$note_number'>".$cl->{note_title}."</a>";
504 $note_number++;
505 }
506 next;
507 }
510 my $output="";
511 # Выводим <head_lines> верхних строк
512 # и <tail_lines> нижних строк,
513 # если эти параметры существуют
515 if ($cl->{"last_command"} eq "cat" && !$cl->{"err"} && !($cl->{"cline"} =~ /</)) {
516 my $filename = $cl->{"cline"};
517 $filename =~ s/.*\s+(\S+)\s*$/$1/;
518 $Files{$filename}->{"content"} = $cl->{"output"};
519 $Files{$filename}->{"source_command_id"} = $cl->{"id"}
520 }
521 my @lines = split '\n', $cl->{"output"};
522 if ((
523 $Config{"head_lines"}
524 || $Config{"tail_lines"}
525 )
526 && $#lines > $Config{"head_lines"} + $Config{"tail_lines"} ) {
528 for (my $i=0; $i<= $#lines && $i < $Config{"head_lines"}; $i++) {
529 $output .= $lines[$i]."\n";
530 }
531 $output .= $Config{"skip_text"}."\n";
533 my $start_line=$#lines-$Config{"tail_lines"}+1;
534 for ($i=$start_line; $i<= $#lines; $i++) {
535 $output .= $lines[$i]."\n";
536 }
537 }
538 else {
539 $ output .= $cl->{"output"};
540 }
542 #
543 ##
544 ## Начинается собственно вывод
545 ##
546 #
548 my ($sec,$min,$hour,$day,$mon,$year,$wday,$yday,$isdst) = localtime($cl->{time});
550 # Добавляем спереди 0 для удобочитаемости
551 $min = "0".$min if $min =~ /^.$/;
552 $hour = "0".$hour if $hour =~ /^.$/;
553 $sec = "0".$sec if $sec =~ /^.$/;
555 $class=$cl->{"class"};
556 $Stat{ErrorCommands}++ if $class =~ /wrong/;
557 $Stat{MistypedCommands}++ if $class =~ /mistype/;
560 # DAY CHANGE
561 if ( $last_day ne $day) {
562 if ($last_day) {
564 # Вычисляем разность множеств.
565 # Что-то вроде этого, если бы так можно было писать:
566 # @new_commands = keys %CommandsFDistribution - @known_commands;
569 $result .= "<h3 id='day$last_day'>".$Day_Name[$last_wday]."</h3>";
573 for my $entry_class (sort keys %new_entries_of) {
574 my $new_commands_section = make_new_entries_table($entry_class=~/[0-9]+\s+(.*)/, \@known_commands);
576 my $table_caption = "Таблица "
577 . $table_number++
578 . ". "
579 . $Day_Name[$last_wday]
580 . ". Новые "
581 . $new_entries_of{$entry_class};
582 if ($new_commands_section) {
583 $result .= "<table class='new_commands_table' width='700' cellspacing='0' cellpadding='0'>"
584 . "<tr class='new_commands_caption'>"
585 . "<td colspan='2' align='right'>$table_caption</td>"
586 . "</tr>"
587 . "<tr class='new_commands_header'>"
588 . "<td width=100>Команда</td><td width=600>Описание</td>"
589 . "</tr>"
590 . $new_commands_section
591 . "</table>"
592 }
594 }
595 @known_commands = keys %CommandsFDistribution;
596 #$result .= "<table width='100%'>\n";
597 $result .= $this_day_result;
598 #$result .= "</table>";
599 }
601 push @toc, "<a href='#day$day'>".$Day_Name[$wday]."</a>\n";
602 $last_day=$day;
603 $last_wday=$wday;
604 $this_day_result = q();
605 }
606 elsif ($seconds_since_last_command > 7200) {
607 my $hours_passed = int($seconds_since_last_command/3600);
608 my $passed_word = $hours_passed % 10 == 1 ? "прошла"
609 : "прошло";
610 my $hours_word = $hours_passed % 10 == 1 ? "часа":
611 "часов";
612 $this_day_result .= "<div class='much_time_passed'>"
613 . $passed_word." &gt;".$hours_passed." ".$hours_word
614 . "</div>\n";
615 }
616 elsif ($seconds_since_last_command > 600) {
617 my $minutes_passed = int($seconds_since_last_command/60);
620 my $passed_word = $minutes_passed % 100 > 10
621 && $minutes_passed % 100 < 20 ? "прошло"
622 : $minutes_passed % 10 == 1 ? "прошла"
623 : "прошло";
625 my $minutes_word = $minutes_passed % 100 > 10
626 && $minutes_passed % 100 < 20 ? "минут" :
627 $minutes_passed % 10 == 1 ? "минута":
628 $minutes_passed % 10 == 0 ? "минут" :
629 $minutes_passed % 10 > 4 ? "минут" :
630 "минуты";
632 if ($seconds_since_last_command < 1800) {
633 $this_day_result .= "<div class='time_passed'>"
634 . $passed_word." ".$minutes_passed." ".$minutes_word
635 . "</div>\n";
636 }
637 else {
638 $this_day_result .= "<div class='much_time_passed'>"
639 . $passed_word." ".$minutes_passed." ".$minutes_word
640 . "</div>\n";
641 }
642 }
644 #$this_day_result .= "<table cellspacing='0' cellpading='0' class='command' id='command:".$cl->{"id"}."' width='100%'><tr>\n";
645 $this_day_result .= "<div class='command' id='command:".$cl->{"id"}."' >\n";
648 # CONSOLE CHANGE
649 if ($cl->{"tty"} && $last_tty ne $cl->{"tty"} && 0) {
650 my $tty = $cl->{"tty"};
651 $this_day_result .= "<div class='ttychange'>"
652 . $tty
653 ."</div>";
654 $last_tty=$cl->{"tty"};
655 }
657 # Session change
658 if ( $last_session ne $cl->{"local_session_id"}) {
659 my $tty = $cl->{"tty"};
660 $this_day_result .= "<a href='?local_session_id=".$cl->{"local_session_id"}."'><div class='ttychange'>"
661 . $Sessions{$cl->{"local_session_id"}}->{"tty"}
662 ."</div></a>";
663 $last_session=$cl->{"local_session_id"};
664 }
666 # TIME
667 $this_day_result .= "<div class='time'>$hour:$min:$sec</div>"
668 if $Config{"show_time"} =~ /^y/i;
670 #$this_day_result .= $Config{"show_time"} =~ /^y/i
671 # ? "<td width='100' valign='top' class='time' width='$Config{time_width}'>$hour:$min:$sec</td>"
672 # : "<td width='0'/>";
674 # CLASS
675 # if ($cl->{"err"}) {
676 # $this_day_result .= "<td width='6' valign='top'>"
677 # . "<table><tr><td width='6' height='6' class='err_box'>"
678 # . "E"
679 # . "</td></tr></table>"
680 # . "</td>";
681 # }
682 # else {
683 # $this_day_result .= "<td width='10' valign='top'>"
684 # . " "
685 # . "</td>";
686 # }
688 # COMMAND
689 my $hint = make_comment($cl->{"cline"});
691 my $cline;
692 $prompt_hint = join ("&#10;", map("$_=$cl->{$_}", grep (!/^(output|diff)$/, sort(keys(%{$cl})))));
693 $cline = "<span title='$prompt_hint'>".$cl->{"prompt"}."</span>".$cl->{"cline"};
694 $cline =~ s/\n//;
696 $cline = "<span title='$hint' class='with_hint'>$cline</span>" if $hint;
697 $cline = "<span class='without_hint'>$cline</span>" if !$hint;
699 $this_day_result .= "<table cellpadding='0' cellspacing='0'><tr><td>\n<div class='cblock_$cl->{class}'>\n";
700 $this_day_result .= "<div class='cline'>\n" . $cline ; #cline
701 $this_day_result .= "<span title='Код завершения ".$cl->{"err"}."'>\n"
702 . "<img src='".$Config{frontend_ico_path}."/error.png'/>\n"
703 . "</span>\n" if $cl->{"err"};
704 $this_day_result .= "</div>\n"; #cline
706 # OUTPUT
707 my $last_command = $cl->{"last_command"};
708 if (!(
709 $Config{"suppress_editors"} =~ /^y/i && grep ($_ eq $last_command, @{$Config{"editors"}}) ||
710 $Config{"suppress_pagers"} =~ /^y/i && grep ($_ eq $last_command, @{$Config{"pagers"}}) ||
711 $Config{"suppress_terminal"}=~ /^y/i && grep ($_ eq $last_command, @{$Config{"terminal"}})
712 )) {
713 $this_day_result .= "<pre class='output'>\n" . $output . "</pre>\n";
714 }
716 # DIFF
717 $this_day_result .= "<pre class='diff'>".$cl->{"diff"}."</pre>"
718 if ( $Config{"show_diffs"} =~ /^y/i && $cl->{"diff"});
719 # SHOT
720 $this_day_result .= "<img src='"
721 .$Config{l3shot_path}
722 .$cl->{"screenshot"}
723 .$Config{l3shot_suffix}
724 ."' alt ='screenshot id ".$cl->{"screenshot"}
725 ."'/>"
726 if ( $Config{"show_screenshots"} =~ /^y/i && $cl->{"screenshot"});
728 #NOTES
729 if ( $Config{"show_notes"} =~ /^y/i && $cl->{"note"}) {
730 my $note=$cl->{"note"};
731 $note =~ s/\n/<br\/>\n/msg;
732 if (not $note =~ s@(http:[a-zA-Z.0-9/_?%-]*)@<a href='$1'>$1</a>@g) {
733 $note =~ s@(www\.[a-zA-Z.0-9/_?%-]*)@<a href='$1'>$1</a>@g;
734 };
735 $this_day_result .= "<div class='note'>";
736 $this_day_result .= "<div class='note_title'>".$cl->{note_title}."</div>" if $cl->{note_title};
737 $this_day_result .= "<div class='note_text'>".$note."</div>";
738 $this_day_result .= "</div>\n";
739 }
741 # COMMENT
742 if ( $Config{"show_comments"} =~ /^y/i) {
743 my $comment = make_comment($cl->{"cline"});
744 if ($comment) {
745 $this_day_result .=
746 "<div class='note' width='100%'>"
747 . $comment
748 . "</div>\n"
749 ;
751 }
752 }
754 # Вывод очередной команды окончен
755 $this_day_result .= "</div>\n"; # cblock
756 $this_day_result .= "</td></tr></table>\n"
757 . "</div>\n"; # command
758 }
759 last: {
760 $result .= "<h3 id='day$last_day'>".$Day_Name[$last_wday]."</h3>";
762 for my $entry_class (keys %new_entries_of) {
763 my $new_commands_section = make_new_entries_table($entry_class=~/[0-9]+\s+(.*)/, \@known_commands);
764 my $table_caption = "Таблица "
765 . $table_number++
766 . ". "
767 . $Day_Name[$last_wday]
768 . ". Новые "
769 . $new_entries_of{$entry_class};
770 if ($new_commands_section) {
771 $result .= "<table class='new_commands_table' width='700' cellspacing='0' cellpadding='0'>"
772 . "<tr class='new_commands_caption'>"
773 . "<td colspan='2' align='right'>$table_caption</td>"
774 . "</tr>"
775 . "<tr class='new_commands_header'>"
776 . "<td width=100>Команда</td><td width=600>Описание</td>"
777 . "</tr>"
778 . $new_commands_section
779 . "</table>"
780 }
782 }
783 @known_commands = keys %CommandsFDistribution;
785 $result .= $this_day_result;
786 }
788 return ($result, collapse_list (\@toc));
790 }
792 sub make_new_entries_table
793 {
794 my $entries_class = shift;
795 my @known_commands = @{$_[0]};
797 my %count;
798 my @new_commands = ();
799 for my $c (keys %CommandsFDistribution, @known_commands) {
800 $count{$c}++
801 }
802 for my $c (keys %CommandsFDistribution) {
803 push @new_commands, $c if $count{$c} != 2;
804 }
807 my $new_commands_section;
808 if (@new_commands){
809 my $hint;
810 for my $c (reverse sort { $CommandsFDistribution{$a} <=> $CommandsFDistribution{$b} } @new_commands) {
811 $hint = make_comment($c);
812 next unless $hint;
813 my ($command, $hint) = $hint =~ m/(.*?) \s*- \s*(.*)/;
814 next unless $command =~ s/\($entries_class\)//i;
815 $new_commands_section .= "<tr><td valign='top'>$command</td><td>$hint</td></tr>";
816 }
817 }
818 return $new_commands_section;
819 }
822 #############
823 # print_all
824 #
825 #
826 #
827 # In: $_[0] output_filename
828 # Out:
831 sub print_all
832 {
833 my $output_filename=$_[0];
835 my $result;
836 my ($command_lines,$toc) = print_command_lines;
837 my $files_section = print_files;
839 $result = print_header($toc);
842 # $result.= join " <br/>", keys %Sessions;
843 # for my $sess (keys %Sessions) {
844 # $result .= join " ", keys (%{$Sessions{$sess}});
845 # $result .= "<br/>";
846 # }
848 $result.= "<h2 id='log'>Журнал</h2>" . $command_lines;
849 $result.= "<h2 id='files'>Файлы</h2>" . $files_section if $files_section;
850 $result.= "<h2 id='stat'>Статистика</h2>" . print_stat;
851 $result.= "<h2 id='help'>Справка</h2>" . $Html_Help . "<br/>";
852 $result.= "<h2 id='about'>О программе</h2>". $Html_About. "<br/>";
853 $result.= print_footer;
855 if ($output_filename eq "-") {
856 print $result;
857 }
858 else {
859 open(OUT, ">", $output_filename)
860 or die "Can't open $output_filename for writing\n";
861 print OUT $result;
862 close(OUT);
863 }
864 }
866 #############
867 # print_header
868 #
869 #
870 #
871 # In: $_[0] Содержание
872 # Out: Распечатанный заголовок
874 sub print_header
875 {
876 my $toc = $_[0];
877 my $course_name = $Config{"course-name"};
878 my $course_code = $Config{"course-code"};
879 my $course_date = $Config{"course-date"};
880 my $course_center = $Config{"course-center"};
881 my $course_trainer = $Config{"course-trainer"};
882 my $course_student = $Config{"course-student"};
884 my $title = "Журнал лабораторных работ";
885 $title .= " -- ".$course_student if $course_student;
886 if ($course_date) {
887 $title .= " -- ".$course_date;
888 $title .= $course_code ? "/".$course_code
889 : "";
890 }
891 else {
892 $title .= " -- ".$course_code if $course_code;
893 }
895 # Управляющая форма
896 my $control_form .= "<div class='visibility_form' title='Выберите какие элементы должны быть показаны в журнале'>"
897 . "<span class='header'>Видимые элементы</span>"
898 . "<span class='window_controls'><a href='' onclick='' title='свернуть форму управления'>_</a> <a href='' onclick='' title='закрыть форму управления'>x</a></span>"
899 . "<div><form>\n";
900 for my $element (sort keys %Elements_Visibility)
901 {
902 my ($skip, @e) = split /\s+/, $element;
903 my $showhide = join "", map { "ShowHide('$_');" } @e ;
904 $control_form .= "<div><input type='checkbox' name='$e[0]' onclick=\"$showhide\" checked>".
905 $Elements_Visibility{$element}.
906 "</input></div>";
907 }
908 $control_form .= "</form>\n"
909 . "</div>\n";
911 my $result;
912 $result = <<HEADER;
913 <html>
914 <head>
915 <meta content='text/html; charset=utf-8' http-equiv='Content-Type' />
916 <link rel='stylesheet' href='$Config{frontend_css}' type='text/css'/>
917 <title>$title</title>
918 </head>
919 <body>
920 <script>
921 $Html_JavaScript
922 </script>
924 <!-- vvv Tigra Hints vvv -->
925 <script language="JavaScript" src="/tigra/hints.js"></script>
926 <script language="JavaScript" src="/tigra/hints_cfg.js"></script>
927 <style>
928 /* a class for all Tigra Hints boxes, TD object */
929 .hintsClass
930 {text-align: center; font-family: Verdana, Arial, Helvetica; padding: 0px 0px 0px 0px;}
931 /* this class is used by Tigra Hints wrappers */
932 .row
933 {background: white;}
934 </style>
935 <!-- ^^^ Tigra Hints ^^^ -->
938 <h1 onmouseover="myHint.show('1')" onmouseout="myHint.hide()">Журнал лабораторных работ</h1>
939 HEADER
940 if ( $course_student
941 || $course_trainer
942 || $course_name
943 || $course_code
944 || $course_date
945 || $course_center) {
946 $result .= "<p>";
947 $result .= "Выполнил $course_student<br/>" if $course_student;
948 $result .= "Проверил $course_trainer <br/>" if $course_trainer;
949 $result .= "Курс " if $course_name
950 || $course_code
951 || $course_date;
952 $result .= "$course_name " if $course_name;
953 $result .= "($course_code)" if $course_code;
954 $result .= ", $course_date<br/>" if $course_date;
955 $result .= "Учебный центр $course_center <br/>" if $course_center;
956 $result .= "Фильтр ".join(" ", map("$filter{$_}=$_", keys %filter))."<br/>" if %filter;
957 $result .= "</p>";
958 }
960 $result .= <<HEADER;
961 <table width='100%'>
962 <tr>
963 <td width='*'>
965 <table border=0 id='toc' class='toc'>
966 <tr>
967 <td>
968 <div class='toc_title'>Содержание</div>
969 <ul>
970 <li><a href='#log'>Журнал</a></li>
971 <ul>$toc</ul>
972 <li><a href='#files'>Файлы</a></li>
973 <li><a href='#stat'>Статистика</a></li>
974 <li><a href='#help'>Справка</a></li>
975 <li><a href='#about'>О программе</a></li>
976 </ul>
977 </td>
978 </tr>
979 </table>
981 </td>
982 <td valign='top' width=200>$control_form</td>
983 </tr>
984 </table>
985 HEADER
987 return $result;
988 }
991 #############
992 # print_footer
993 #
994 #
995 #
996 #
997 #
999 sub print_footer
1001 return "</body>\n</html>\n";
1007 #############
1008 # print_stat
1012 # In:
1013 # Out:
1015 sub print_stat
1017 %StatNames = (
1018 FirstCommand => "Время первой команды журнала",
1019 LastCommand => "Время последней команды журнала",
1020 TotalCommands => "Количество командных строк в журнале",
1021 ErrorsPercentage => "Процент команд с ненулевым кодом завершения, %",
1022 MistypesPercentage => "Процент синтаксически неверно набранных команд, %",
1023 TotalTime => "Суммарное время работы с терминалом <sup><font size='-2'>*</font></sup>, час",
1024 CommandsPerTime => "Количество командных строк в единицу времени, команда/мин",
1025 CommandsFrequency => "Частота использования команд",
1026 RareCommands => "Частота использования этих команд < 0.5%",
1027 );
1028 @StatOrder = (
1029 FirstCommand,
1030 LastCommand,
1031 TotalCommands,
1032 ErrorsPercentage,
1033 MistypesPercentage,
1034 TotalTime,
1035 CommandsPerTime,
1036 CommandsFrequency,
1037 RareCommands,
1038 );
1040 # Подготовка статистики к выводу
1041 # Некоторые значения пересчитываются!
1042 # Дальше их лучше уже не использовать!!!
1044 my %CommandsFrequency = %CommandsFDistribution;
1046 $Stat{TotalTime} ||= 0;
1047 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($Stat{FirstCommand} || 0);
1048 $Stat{FirstCommand} = sprintf "%02i:%02i:%02i %04i-%2i-%2i", $hour, $min, $sec, $year+1900, $mon+1, $mday;
1049 ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($Stat{LastCommand} || 0);
1050 $Stat{LastCommand} = sprintf "%02i:%02i:%02i %04i-%2i-%2i", $hour, $min, $sec, $year+1900, $mon+1, $mday;
1051 if ($Stat{TotalCommands}) {
1052 $Stat{ErrorsPercentage} = sprintf "%5.2f", $Stat{ErrorCommands}*100/$Stat{TotalCommands};
1053 $Stat{MistypesPercentage} = sprintf "%5.2f", $Stat{MistypedCommands}*100/$Stat{TotalCommands};
1055 $Stat{CommandsPerTime} = sprintf "%5.2f", $Stat{TotalCommands}*60/$Stat{TotalTime}
1056 if $Stat{TotalTime};
1057 $Stat{TotalTime} = sprintf "%5.2f", $Stat{TotalTime}/60/60;
1059 my $total_commands=0;
1060 for $command (keys %CommandsFrequency){
1061 $total_commands += $CommandsFrequency{$command};
1063 if ($total_commands) {
1064 for $command (reverse sort {$CommandsFrequency{$a} <=> $CommandsFrequency{$b}} keys %CommandsFrequency){
1065 my $command_html;
1066 my $percentage = sprintf "%5.2f",$CommandsFrequency{$command}*100/$total_commands;
1067 if ($percentage < 0.5) {
1068 my $hint = make_comment($command);
1069 $command_html = "$command";
1070 $command_html = "<span title='$hint' class='with_hint'>$command_html</span>" if $hint;
1071 $command_html = "<span class='without_hint'>$command_html</span>" if not $hint;
1072 my $command_html = "<tt>$command_html</tt>";
1073 $Stat{RareCommands} .= $command_html."<sub><font size='-2'>".$CommandsFrequency{$command}."</font></sub> , ";
1075 else {
1076 my $hint = make_comment($command);
1077 $command_html = "$command";
1078 $command_html = "<span title='$hint' class='with_hint'>$command_html</span>" if $hint;
1079 $command_html = "<span class='without_hint'>$command_html</span>" if not $hint;
1080 my $command_html = "<tt>$command_html</tt>";
1081 $percentage = sprintf "%5.2f",$percentage;
1082 $Stat{CommandsFrequency} .= "<tr><td>".$command_html."</td><td>".$CommandsFrequency{$command}."</td>".
1083 "<td>|".("="x int($CommandsFrequency{$command}*100/$total_commands))."| $percentage%</td></tr>";
1086 $Stat{CommandsFrequency} = "<table>".$Stat{CommandsFrequency}."</table>";
1087 $Stat{RareCommands} =~ s/, $// if $Stat{RareCommands};
1090 my $result = q();
1091 for my $stat (@StatOrder) {
1092 next unless $Stat{"$stat"};
1093 $result .= "<tr valign='top'><td width='300'>".$StatNames{"$stat"}."</td><td>".$Stat{"$stat"}."</td></tr>"
1095 $result = "<table>$result</table>"
1096 . "<font size='-2'>____<br/>*) Интервалы неактивности длительностью "
1097 . ($Config{stat_inactivity_interval}/60)
1098 . " минут и более не учитываются</font></br>";
1100 return $result;
1104 sub collapse_list($)
1106 my $res = "";
1107 for my $elem (@{$_[0]}) {
1108 if (ref $elem eq "ARRAY") {
1109 $res .= "<ul>".collapse_list($elem)."</ul>";
1111 else
1113 $res .= "<li>".$elem."</li>";
1116 return $res;
1120 sub print_files
1122 my $result = qq();
1123 my @toc;
1124 for my $file (sort keys %Files) {
1125 my $div_id = "file:$file";
1126 $div_id =~ s@/@_@g;
1127 push @toc, "<a href='#$div_id'>$file</a>";
1128 $result .= "<div class='filename' id='$div_id'>".$file."</div>\n"
1129 . "<div class='file_navigation'><a href='#command:".$Files{$file}->{source_command_id}."'>"."&gt;"."</a></div>"
1130 . "<div class='filedata'><pre>".$Files{$file}->{content}."</pre></div>";
1132 return "<div class='files_toc'>".collapse_list(\@toc)."</div>".$result;
1136 sub init_variables
1138 $Html_Help = <<HELP;
1139 Для того чтобы использовать LiLaLo, не нужно знать ничего особенного:
1140 всё происходит само собой.
1141 Однако, чтобы ведение и последующее использование журналов
1142 было как можно более эффективным, желательно иметь в виду следующее:
1143 <ol>
1144 <li><p>
1145 В журнал автоматически попадают все команды, данные в любом терминале системы.
1146 </p></li>
1147 <li><p>
1148 Для того чтобы убедиться, что журнал на текущем терминале ведётся,
1149 и команды записываются, дайте команду w.
1150 В поле WHAT, соответствующем текущему терминалу,
1151 должна быть указана программа script.
1152 </p></li>
1153 <li><p>
1154 Команды, при наборе которых были допущены синтаксические ошибки,
1155 выводятся перечёркнутым текстом:
1156 <table>
1157 <tr class='command'>
1158 <td class='script'>
1159 <pre class='_mistyped_cline'>
1160 \$ l s-l</pre>
1161 <pre class='_mistyped_output'>bash: l: command not found
1162 </pre>
1163 </td>
1164 </tr>
1165 </table>
1166 <br/>
1167 </p></li>
1168 <li><p>
1169 Если код завершения команды равен нулю,
1170 команда была выполнена без ошибок.
1171 Команды, код завершения которых отличен от нуля, выделяются цветом.
1172 <table>
1173 <tr class='command'>
1174 <td class='script'>
1175 <pre class='_wrong_cline'>
1176 \$ test 5 -lt 4</pre>
1177 </pre>
1178 </td>
1179 </tr>
1180 </table>
1181 Обратите внимание на то, что код завершения команды может быть отличен от нуля
1182 не только в тех случаях, когда команда была выполнена с ошибкой.
1183 Многие команды используют код завершения, например, для того чтобы показать результаты проверки
1184 <br/>
1185 </p></li>
1186 <li><p>
1187 Команды, ход выполнения которых был прерван пользователем, выделяются цветом.
1188 <table>
1189 <tr class='command'>
1190 <td class='script'>
1191 <pre class='_interrupted_cline'>
1192 \$ find / -name abc</pre>
1193 <pre class='interrupted_output'>find: /home/devi-orig/.gnome2: Keine Berechtigung
1194 find: /home/devi-orig/.gnome2_private: Keine Berechtigung
1195 find: /home/devi-orig/.nautilus/metafiles: Keine Berechtigung
1196 find: /home/devi-orig/.metacity: Keine Berechtigung
1197 find: /home/devi-orig/.inkscape: Keine Berechtigung
1198 ^C
1199 </pre>
1200 </td>
1201 </tr>
1202 </table>
1203 <br/>
1204 </p></li>
1205 <li><p>
1206 Команды, выполненные с привилегиями суперпользователя,
1207 выделяются слева красной чертой.
1208 <table>
1209 <tr class='command'>
1210 <td class='script'>
1211 <pre class='_root_cline'>
1212 # id</pre>
1213 <pre class='_root_output'>
1214 uid=0(root) gid=0(root) Gruppen=0(root)
1215 </pre>
1216 </td>
1217 </tr>
1218 </table>
1219 <br/>
1220 </p></li>
1221 <li><p>
1222 Изменения, внесённые в текстовый файл с помощью редактора,
1223 запоминаются и показываются в журнале в формате ed.
1224 Строки, начинающиеся символом "&lt;", удалены, а строки,
1225 начинающиеся символом "&gt;" -- добавлены.
1226 <table>
1227 <tr class='command'>
1228 <td class='script'>
1229 <pre class='cline'>
1230 \$ vi ~/.bashrc</pre>
1231 <table><tr><td width='5'/><td class='diff'><pre>2a3,5
1232 &gt; if [ -f /usr/local/etc/bash_completion ]; then
1233 &gt; . /usr/local/etc/bash_completion
1234 &gt; fi
1235 </pre></td></tr></table></td>
1236 </tr>
1237 </table>
1238 <br/>
1239 </p></li>
1240 <li><p>
1241 Для того чтобы изменить файл в соответствии с показанными в диффшоте
1242 изменениями, можно воспользоваться командой patch.
1243 Нужно скопировать изменения, запустить программу patch, указав в
1244 качестве её аргумента файл, к которому применяются изменения,
1245 и всавить скопированный текст:
1246 <table>
1247 <tr class='command'>
1248 <td class='script'>
1249 <pre class='cline'>
1250 \$ patch ~/.bashrc</pre>
1251 </td>
1252 </tr>
1253 </table>
1254 В данном случае изменения применяются к файлу ~/.bashrc
1255 </p></li>
1256 <li><p>
1257 Для того чтобы получить краткую справочную информацию о команде,
1258 нужно подвести к ней мышь. Во всплывающей подсказке появится краткое
1259 описание команды.
1260 </p>
1261 <p>
1262 Если справочная информация о команде есть,
1263 команда выделяется голубым фоном, например: <span class="with_hint" title="главный текстовый редактор Unix">vi</span>.
1264 Если справочная информация отсутствует,
1265 команда выделяется розовым фоном, например: <span class="without_hint">notepad.exe</span>.
1266 Справочная информация может отсутствовать в том случае,
1267 если (1) команда введена неверно; (2) если распознавание команды LiLaLo выполнено неверно;
1268 (3) если информация о команде неизвестна LiLaLo.
1269 Последнее возможно для редких команд.
1270 </p></li>
1271 <li><p>
1272 Большие, в особенности многострочные, всплывающие подсказки лучше
1273 всего показываются браузерами KDE Konqueror, Apple Safari и Microsoft Internet Explorer.
1274 В браузерах Mozilla и Firefox они отображаются не полностью,
1275 а вместо перевода строки выводится специальный символ.
1276 </p></li>
1277 <li><p>
1278 Время ввода команды, показанное в журнале, соответствует времени
1279 <i>начала ввода командной строки</i>, которое равно тому моменту,
1280 когда на терминале появилось приглашение интерпретатора
1281 </p></li>
1282 <li><p>
1283 Имя терминала, на котором была введена команда, показано в специальном блоке.
1284 Этот блок показывается только в том случае, если терминал
1285 текущей команды отличается от терминала предыдущей.
1286 </p></li>
1287 <li><p>
1288 Вывод не интересующих вас в настоящий момент элементов журнала,
1289 таких как время, имя терминала и других, можно отключить.
1290 Для этого нужно воспользоваться <a href='#visibility_form'>формой управления журналом</a>
1291 вверху страницы.
1292 </p></li>
1293 <li><p>
1294 Небольшие комментарии к командам можно вставлять прямо из командной строки.
1295 Комментарий вводится прямо в командную строку, после символов #^ или #v.
1296 Символы ^ и v показывают направление выбора команды, к которой относится комментарий:
1297 ^ - к предыдущей, v - к следующей.
1298 Например, если в командной строке было введено:
1299 <pre class='cline'>
1300 \$ whoami
1301 </pre>
1302 <pre class='output'>
1303 user
1304 </pre>
1305 <pre class='cline'>
1306 \$ #^ Интересно, кто я?
1307 </pre>
1308 в журнале это будет выглядеть так:
1310 <pre class='cline'>
1311 \$ whoami
1312 </pre>
1313 <pre class='output'>
1314 user
1315 </pre>
1316 <table class='note'><tr><td width='100%' class='note_text'>
1317 <tr> <td> Интересно, кто я?<br/> </td></tr></table>
1318 </p></li>
1319 <li><p>
1320 Если комментарий содержит несколько строк,
1321 его можно вставить в журнал следующим образом:
1322 <pre class='cline'>
1323 \$ whoami
1324 </pre>
1325 <pre class='output'>
1326 user
1327 </pre>
1328 <pre class='cline'>
1329 \$ cat > /dev/null #^ Интересно, кто я?
1330 </pre>
1331 <pre class='output'>
1332 Программа whoami выводит имя пользователя, под которым
1333 мы зарегистрировались в системе.
1335 Она не может ответить на вопрос о нашем назначении
1336 в этом мире.
1337 </pre>
1338 В журнале это будет выглядеть так:
1339 <table>
1340 <tr class='command'>
1341 <td class='script'>
1342 <pre class='cline'>
1343 \$ whoami</pre>
1344 <pre class='output'>user
1345 </pre>
1346 <table class='note'><tr><td class='note_title'>Интересно, кто я?</td></tr><tr><td width='100%' class='note_text'>
1347 Программа whoami выводит имя пользователя, под которым<br/>
1348 мы зарегистрировались в системе.<br/>
1349 <br/>
1350 Она не может ответить на вопрос о нашем назначении<br/>
1351 в этом мире.<br/>
1352 </td></tr></table>
1353 </td>
1354 </tr>
1355 </table>
1356 Для разделения нескольких абзацев между собой
1357 используйте символ "-", один в строке.
1358 <br/>
1359 </p></li>
1360 <li><p>
1361 Комментарии, не относящиеся непосредственно ни к какой из команд,
1362 добавляются точно таким же способом, только вместо симолов #^ или #v
1363 нужно использовать символы #=
1364 </p></li>
1365 </ol>
1366 HELP
1368 $Html_About = <<ABOUT;
1369 <p>
1370 LiLaLo (L3) расшифровывается как Live Lab Log.<br/>
1371 Программа разработана для повышения эффективности обучения Unix/Linux-системам.<br/>
1372 (c) Игорь Чубин, 2004-2006<br/>
1373 </p>
1374 ABOUT
1375 $Html_About.='$Id$ </p>';
1377 $Html_JavaScript = <<JS;
1378 function getElementsByClassName(Class_Name)
1380 var Result=new Array();
1381 var All_Elements=document.all || document.getElementsByTagName('*');
1382 for (i=0; i<All_Elements.length; i++)
1383 if (All_Elements[i].className==Class_Name)
1384 Result.push(All_Elements[i]);
1385 return Result;
1387 function ShowHide (name)
1389 elements=getElementsByClassName(name);
1390 for(i=0; i<elements.length; i++)
1391 if (elements[i].style.display == "none")
1392 elements[i].style.display = "";
1393 else
1394 elements[i].style.display = "none";
1395 //if (elements[i].style.visibility == "hidden")
1396 // elements[i].style.visibility = "visible";
1397 //else
1398 // elements[i].style.visibility = "hidden";
1400 function filter_by_output(text)
1403 var jjj=0;
1405 elements=getElementsByClassName('command');
1406 for(i=0; i<elements.length; i++) {
1407 subelems = elements[i].getElementsByTagName('pre');
1408 for(j=0; j<subelems.length; j++) {
1409 if (subelems[j].className = 'output') {
1410 var str = new String(subelems[j].nodeValue);
1411 if (jjj != 1) {
1412 alert(str);
1413 jjj=1;
1415 if (str.indexOf(text) >0)
1416 subelems[j].style.display = "none";
1417 else
1418 subelems[j].style.display = "";
1426 JS
1428 %Search_Machines = (
1429 "google" => { "query" => "http://www.google.com/search?q=" ,
1430 "icon" => "$Config{frontend_google_ico}" },
1431 "freebsd" => { "query" => "http://www.freebsd.org/cgi/man.cgi?query=",
1432 "icon" => "$Config{frontend_freebsd_ico}" },
1433 "linux" => { "query" => "http://man.he.net/?topic=",
1434 "icon" => "$Config{frontend_linux_ico}"},
1435 "opennet" => { "query" => "http://www.opennet.ru/search.shtml?words=",
1436 "icon" => "$Config{frontend_opennet_ico}"},
1437 "local" => { "query" => "http://www.freebsd.org/cgi/man.cgi?query=",
1438 "icon" => "$Config{frontend_local_ico}" },
1440 );
1442 %Elements_Visibility = (
1443 "0 new_commands_table" => "новые команды",
1444 "1 diff" => "редактор",
1445 "2 time" => "время",
1446 "3 ttychange" => "терминал",
1447 "4 wrong_output wrong_cline wrong_root_output wrong_root_cline"
1448 => "команды с ненулевым кодом завершения",
1449 "5 mistyped_output mistyped_cline mistyped_root_output mistyped_root_cline"
1450 => "неверно набранные команды",
1451 "6 interrupted_output interrupted_cline interrupted_root_output interrupted_root_cline"
1452 => "прерванные команды",
1453 "7 tab_completion_output tab_completion_cline"
1454 => "продолжение с помощью tab"
1455 );
1457 @Day_Name = qw/ Воскресенье Понедельник Вторник Среда Четверг Пятница Суббота /;
1458 @Month_Name = qw/ Январь Февраль Март Апрель Май Июнь Июль Август Сентябрь Октябрь Ноябрь Декабрь /;
1459 @Of_Month_Name = qw/ Января Февраля Марта Апреля Мая Июня Июля Августа Сентября Октября Ноября Декабря /;
1465 # Временно удалённый код
1466 # Возможно, он не понадобится уже никогда
1469 sub search_by
1471 my $sm = shift;
1472 my $topic = shift;
1473 $topic =~ s/ /+/;
1475 return "<a href='". $Search_Machines{$sm}->{"query"}."$topic'><img width='16' height='16' src='".
1476 $Search_Machines{$sm}->{"icon"}."' border='0'/></a>";