lilalo

view l3-frontend @ 88:385499ec544a

Начал работу над текстовым представлением +
редактором журнала.
Пока что в textarea выводится текстовое представление.

Редактировать можно, но сохранять пока нельзя.

Пытался сделать автоматическое позиционирование курсора
на нужную строку.
Во-первых, не работает в Konqueror и с этим, я так понимаю,
ничего пока сделать нельзя.

Во-вторых, неверно вычисляется строка на которую нужно
позиционировать курсор.

Это, я думаю, можно подправить.

Потом, что-то намутил с utf8. Надо будет более детально
это рассмотреть
author devi
date Thu Mar 02 00:06:54 2006 +0200 (2006-03-02)
parents c70be67ed3d4
children 62001c1e3295
line source
1 #!/usr/bin/perl -w
3 use IO::Socket;
4 use lib '.';
5 use l3config;
6 use utf8;
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 %frequency_of_command; # Сколько раз в журнале встречается какая команда
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 minutes_passed;
44 sub print_all_txt;
45 sub print_all_html;
46 sub print_command_lines_html;
47 sub print_files_html;
48 sub print_stat_html;
49 sub print_header_html;
50 sub print_footer_html;
52 main();
54 sub main
55 {
56 $| = 1;
58 init_variables();
59 init_config();
60 $Config{frontend_ico_path}=$Config{frontend_css};
61 $Config{frontend_ico_path}=~s@/[^/]*$@@;
63 open_mywi_socket();
64 load_command_lines_from_xml($Config{"backend_datafile"});
65 load_sessions_from_xml($Config{"backend_datafile"});
66 sort_command_lines;
67 process_command_lines;
68 print_all_txt($Config{"output"});
69 close_mywi_socket;
70 }
72 # extract_from_cline
74 # In: $what = commands | args
75 # Out: return ссылка на хэш, содержащий результаты разбора
76 # команда => позиция
78 # Разобрать командную строку $_[1] и возвратить хэш, содержащий
79 # номер первого появление команды в строке:
80 # команда => первая позиция
81 sub extract_from_cline
82 {
83 my $what = $_[0];
84 my $cline = $_[1];
85 my @lists = split /\;/, $cline;
88 my @command_lines = ();
89 for my $command_list (@lists) {
90 push(@command_lines, split(/\|/, $command_list));
91 }
93 my %position_of_command;
94 my %position_of_arg;
95 my $i=0;
96 for my $command_line (@command_lines) {
97 $command_line =~ s@^\s*@@;
98 $command_line =~ /\s*(\S+)\s*(.*)/;
99 if ($1 && $1 eq "sudo" ) {
100 $position_of_command{"$1"}=$i++;
101 $command_line =~ s/\s*sudo\s+//;
102 }
103 if ($command_line !~ m@^\s*\S*/etc/@) {
104 $command_line =~ s@^\s*\S+/@@;
105 }
107 $command_line =~ /\s*(\S+)\s*(.*)/;
108 my $command = $1;
109 my $args = $2;
110 if ($command && !defined $position_of_command{"$command"}) {
111 $position_of_command{"$command"}=$i++;
112 };
113 if ($args) {
114 my @args = split (/\s+/, $args);
115 for my $a (@args) {
116 $position_of_arg{"$a"}=$i++
117 if !defined $position_of_arg{"$a"};
118 };
119 }
120 }
122 if ($what eq "commands") {
123 return \%position_of_command;
124 } else {
125 return \%position_of_arg;
126 }
128 }
133 #
134 # Подпрограммы для работы с mywi
135 #
137 sub open_mywi_socket
138 {
139 $Mywi_Socket = IO::Socket::INET->new(
140 PeerAddr => $Config{mywi_server},
141 PeerPort => $Config{mywi_port},
142 Proto => "tcp",
143 Type => SOCK_STREAM);
144 }
146 sub close_mywi_socket
147 {
148 close ($Mywi_Socket) if $Mywi_Socket ;
149 }
152 sub mywi_client
153 {
154 my $query = $_[0];
155 my $mywi;
157 open_mywi_socket;
158 if ($Mywi_Socket) {
159 local $| = 1;
160 local $/ = "";
161 print $Mywi_Socket $query."\n";
162 $mywi = <$Mywi_Socket>;
163 $mywi = "" if $mywi =~ /nothing app/;
164 }
165 close_mywi_socket;
166 return $mywi;
167 }
169 sub make_comment
170 {
171 my $cline = $_[0];
172 #my $files = $_[1];
174 my @comments;
175 my @commands = keys %{extract_from_cline("commands", $cline)};
176 my @args = keys %{extract_from_cline("args", $cline)};
177 return if (!@commands && !@args);
178 #return "commands=".join(" ",@commands)."; files=".join(" ",@files);
180 # Commands
181 for my $command (@commands) {
182 $command =~ s/'//g;
183 $frequency_of_command{$command}++;
184 if (!$Commands_Description{$command}) {
185 $mywi_cache_for{$command} ||= mywi_client ($command) || "";
186 my $mywi = join ("\n", grep(/\([18]|sh|script\)/, split(/\n/, $mywi_cache_for{$command})));
187 $mywi =~ s/\s+/ /;
188 if ($mywi !~ /^\s*$/) {
189 $Commands_Description{$command} = $mywi;
190 }
191 else {
192 next;
193 }
194 }
196 push @comments, $Commands_Description{$command};
197 }
198 return join("&#10;\n", @comments);
200 # Files
201 for my $arg (@args) {
202 $arg =~ s/'//g;
203 if (!$Args_Description{$arg}) {
204 my $mywi;
205 $mywi = mywi_client ($arg);
206 $mywi = join ("\n", grep(/\([5]\)/, split(/\n/, $mywi)));
207 $mywi =~ s/\s+/ /;
208 if ($mywi !~ /^\s*$/) {
209 $Args_Description{$arg} = $mywi;
210 }
211 else {
212 next;
213 }
214 }
216 push @comments, $Args_Description{$arg};
217 }
219 }
221 =cut
222 Процедура load_command_lines_from_xml выполняет загрузку разобранного lab-скрипта
223 из XML-документа в переменную @Command_Lines
225 # In: $datafile имя файла
226 # Out: @CommandLines загруженные командные строки
228 Предупреждение!
229 Процедура не в состоянии обрабатывать XML-документ любой структуры.
230 В действительности файл cache из которого загружаются данные
231 просто напоминает XML с виду.
232 =cut
233 sub load_command_lines_from_xml
234 {
235 my $datafile = $_[0];
237 open (CLASS, $datafile)
238 or die "Can't open file with xml lablog ",$datafile,"\n";
239 local $/;
240 $data = <CLASS>;
241 close(CLASS);
243 for $command ($data =~ m@<command>(.*?)</command>@sg) {
244 my %cl;
245 while ($command =~ m@<([^>]*?)>(.*?)</\1>@sg) {
246 $cl{$1} = $2;
247 }
248 push @Command_Lines, \%cl;
249 }
250 }
252 sub load_sessions_from_xml
253 {
254 my $datafile = $_[0];
256 open (CLASS, $datafile)
257 or die "Can't open file with xml lablog ",$datafile,"\n";
258 local $/;
259 my $data = <CLASS>;
260 close(CLASS);
262 my $i=0;
263 for my $session ($data =~ m@<session>(.*?)</session>@msg) {
264 my %session_hash;
265 while ($session =~ m@<([^>]*?)>(.*?)</\1>@sg) {
266 $session_hash{$1} = $2;
267 }
268 $Sessions{$session_hash{local_session_id}} = \%session_hash;
269 }
270 }
273 # sort_command_lines
274 # In: @Command_Lines
275 # Out: @Command_Lies_Index
277 sub sort_command_lines
278 {
280 my @index;
281 for (my $i=0;$i<=$#Command_Lines;$i++) {
282 $index[$i]=$i;
283 }
285 @Command_Lines_Index = sort {
286 $Command_Lines[$index[$a]]->{"time"} <=> $Command_Lines[$index[$b]]->{"time"}
287 } @index;
289 }
291 ##################
292 # process_command_lines
293 #
294 # Обрабатываются командные строки @Command_Lines
295 # Для каждой строки определяется:
296 # class класс
297 # note комментарий
298 #
299 # In: @Command_Lines_Index
300 # In-Out: @Command_Lines
302 sub process_command_lines
303 {
304 for my $i (@Command_Lines_Index) {
305 my $cl = \$Command_Lines[$i];
307 next if !$cl;
309 $$cl->{id} = $$cl->{"time"};
311 $$cl->{err} ||=0;
313 # Класс команды
315 $$cl->{"class"} = $$cl->{"err"} eq 130 ? "interrupted"
316 : $$cl->{"err"} eq 127 ? "mistyped"
317 : $$cl->{"err"} ? "wrong"
318 : "normal";
320 if ($$cl->{"cline"} &&
321 $$cl->{"cline"} =~ /[^|`]\s*sudo/
322 || $$cl->{"uid"} eq 0) {
323 $$cl->{"class"}.="_root";
324 }
326 # my $hint;
327 # $hint = make_comment($$cl->{"cline"});
328 # if ($hint) {
329 # $$cl->{hint} = $hint;
330 # }
331 $$cl->{hint}="";
333 # Выводим <head_lines> верхних строк
334 # и <tail_lines> нижних строк,
335 # если эти параметры существуют
336 my $output="";
338 if ($$cl->{"last_command"} eq "cat" && !$$cl->{"err"} && !($$cl->{"cline"} =~ /</)) {
339 my $filename = $$cl->{"cline"};
340 $filename =~ s/.*\s+(\S+)\s*$/$1/;
341 $Files{$filename}->{"content"} = $$cl->{"output"};
342 $Files{$filename}->{"source_command_id"} = $$cl->{"id"}
343 }
344 my @lines = split '\n', $$cl->{"output"};
345 if ((
346 $Config{"head_lines"}
347 || $Config{"tail_lines"}
348 )
349 && $#lines > $Config{"head_lines"} + $Config{"tail_lines"} ) {
350 #
351 for (my $i=0; $i<= $#lines && $i < $Config{"head_lines"}; $i++) {
352 $output .= $lines[$i]."\n";
353 }
354 $output .= $Config{"skip_text"}."\n";
356 my $start_line=$#lines-$Config{"tail_lines"}+1;
357 for (my $i=$start_line; $i<= $#lines; $i++) {
358 $output .= $lines[$i]."\n";
359 }
360 }
361 else {
362 $output = $$cl->{"output"};
363 }
364 $$cl->{short_output} = $output;
366 #Обработка пометок
367 # Если несколько пометок (notes) идут подряд,
368 # они все объединяются
370 if ($$cl->{cline} =~ /l3shot/) {
371 if ($$cl->{output} =~ m@Screenshot is written to.*/(.*)\.xwd@) {
372 $$cl->{screenshot}="$1";
373 }
374 }
376 if ($$cl->{cline}=~ m@cat[^#]*#([\^=v])\s*(.*)@) {
378 my $note_operator = $1;
379 my $note_title = $2;
381 if ($note_operator eq "=") {
382 $$cl->{"class"} = "note";
383 $$cl->{"note"} = $$cl->{"output"};
384 $$cl->{"note_title"} = $2;
385 }
386 else {
387 my $j = $i;
388 if ($note_operator eq "^") {
389 $j--;
390 $j-- while ($j >=0 && (!$Command_Lines[$j] || $Command_Lines[$j]->{tty} ne $$cl->{tty}));
391 }
392 elsif ($note_operator eq "v") {
393 $j++;
394 $j++ while ($j <= @Command_Lines && (!$Command_Lines[$j] || $Command_Lines[$j]->{tty} ne $$cl->{tty}));
395 }
396 $Command_Lines[$j]->{note_title}=$note_title;
397 $Command_Lines[$j]->{note}.=$$cl->{output};
398 $$cl=0;
399 }
400 }
401 elsif ($$cl->{cline}=~ /#([\^=v])(.*)/) {
403 my $note_operator = $1;
404 my $note_text = $2;
406 if ($note_operator eq "=") {
407 $$cl->{"class"} = "note";
408 $$cl->{"note"} = $note_text;
409 }
410 else {
411 my $j=$i;
412 if ($note_operator eq "^") {
413 $j--;
414 $j-- while ($j >=0 && (!$Command_Lines[$j] || $Command_Lines[$j]->{tty} ne $$cl->{tty}));
415 }
416 elsif ($note_operator eq "v") {
417 $j++;
418 $j++ while ($j <= @Command_Lines && $Command_Lines[$j]->{tty} ne $$cl->{tty} || !$Command_Lines[$j]);
419 }
420 $Command_Lines[$j]->{note}.="$note_text\n";
421 $$cl=0;
422 }
423 }
424 if ($$cl->{"class"} eq "note") {
425 my $note_html = $$cl->{note};
426 $note_html = join ("\n", map ("<p>$_</p>", split (/-\n/, $note_html)));
427 $note_html =~ s@(http:[a-zA-Z.0-9/?\_%-]*)@<a href='$1'>$1</a>@g;
428 $note_html =~ s@(www\.[a-zA-Z.0-9/?\_%-]*)@<a href='$1'>$1</a>@g;
429 $$cl->{"note_html"} = $note_html;
430 }
431 }
433 }
436 =cut
437 Процедура print_command_lines выводит HTML-представление
438 разобранного lab-скрипта.
440 Разобранный lab-скрипт должен находиться в массиве @Command_Lines
441 =cut
443 sub print_command_lines_html
444 {
446 my @toc; # Оглавление
447 my $note_number=0;
449 my $result = q();
450 my $this_day_resut = q();
452 my $cl;
453 my $last_tty="";
454 my $last_session="";
455 my $last_day=q();
456 my $last_wday=q();
457 my $in_range=0;
459 my $current_command=0;
461 my @known_commands;
464 if ($Config{filter}) {
465 # Инициализация фильтра
466 for (split /&/,$Config{filter}) {
467 my ($var, $val) = split /=/;
468 $filter{$var} = $val || "";
469 }
470 }
472 $Stat{LastCommand} ||= 0;
473 $Stat{TotalCommands} ||= 0;
474 $Stat{ErrorCommands} ||= 0;
475 $Stat{MistypedCommands} ||= 0;
477 my %new_entries_of = (
478 "1 1" => "программы пользователя",
479 "2 8" => "программы администратора",
480 "3 sh" => "команды интерпретатора",
481 "4 script"=> "скрипты",
482 );
484 COMMAND_LINE:
485 for my $k (@Command_Lines_Index) {
487 my $cl=$Command_Lines[$Command_Lines_Index[$current_command++]];
488 next unless $cl;
490 # Пропускаем команды, с одинаковым временем
491 # Это не совсем правильно.
492 # Возможно, что это команды, набираемые с помощью <completion>
493 # или запомненные с помощью <ctrl-c>
495 next if $Stat{LastCommand} == $cl->{time};
497 # Пропускаем строки, которые противоречат фильтру
498 # Если у нас недостаточно информации о том, подходит строка под фильтр или нет,
499 # мы её выводим
501 for my $filter_key (keys %filter) {
502 next COMMAND_LINE
503 if defined($cl->{local_session_id})
504 && defined($Sessions{$cl->{local_session_id}}->{$filter_key})
505 && $Sessions{$cl->{local_session_id}}->{$filter_key} ne $filter{$filter_key};
506 }
508 # Набираем статистику
509 # Хэш %Stat
511 $Stat{FirstCommand} = $cl->{time} unless $Stat{FirstCommand};
512 if ($cl->{time} - $Stat{LastCommand} < $Config{stat_inactivity_interval}) {
513 $Stat{TotalTime} += $cl->{time} - $Stat{LastCommand}
514 }
515 my $seconds_since_last_command = $cl->{time} - $Stat{LastCommand};
517 if ($Stat{LastCommand} > $cl->{time}) {
518 $result .= "Время идёт вспять<br/>";
519 };
520 $Stat{LastCommand} = $cl->{time};
521 $Stat{TotalCommands}++;
523 # Пропускаем строки, выходящие за границу "signature",
524 # при условии, что границы указаны
525 # Пропускаем неправильные/прерванные/другие команды
526 if ($Config{"from"} && $cl->{"cline"} =~ /$Config{"signature"}\s*$Config{"from"}/) {
527 $in_range=1;
528 next;
529 }
530 if ($Config{"to"} && $cl->{"cline"} =~ /$Config{"signature"}\s*$Config{"to"}/) {
531 $in_range=0;
532 next;
533 }
534 next if ($Config{"from"} && $Config{"to"} && !$in_range)
535 || ($Config{"skip_empty"} =~ /^y/i && $cl->{"cline"} =~ /^\s*$/ )
536 || ($Config{"skip_wrong"} =~ /^y/i && $cl->{"err"} != 0)
537 || ($Config{"skip_interrupted"} =~ /^y/i && $cl->{"err"} == 130);
542 #
543 ##
544 ## Начинается собственно вывод
545 ##
546 #
548 ### Сначала обрабатываем границы разделов
549 ### Если тип команды "note", это граница
551 if ($cl->{class} eq "note") {
552 $this_day_result .= "<tr><td colspan='6'>"
553 . "<h4 id='note$note_number'>".$cl->{note_title}."</h4>" if $cl->{note_title}
554 . "".$cl->{note_html}."<p/><p/></td></tr>";
556 if ($cl->{note_title}) {
557 push @{$toc[@toc]},"<a href='#note$note_number'>".$cl->{note_title}."</a>";
558 $note_number++;
559 }
560 next;
561 }
563 my ($sec,$min,$hour,$day,$mon,$year,$wday,$yday,$isdst) = localtime($cl->{time});
565 # Добавляем спереди 0 для удобочитаемости
566 $min = "0".$min if $min =~ /^.$/;
567 $hour = "0".$hour if $hour =~ /^.$/;
568 $sec = "0".$sec if $sec =~ /^.$/;
570 $class=$cl->{"class"};
571 $Stat{ErrorCommands}++ if $class =~ /wrong/;
572 $Stat{MistypedCommands}++ if $class =~ /mistype/;
574 # DAY CHANGE
575 if ( $last_day ne $day) {
576 if ($last_day) {
578 # Вычисляем разность множеств.
579 # Что-то вроде этого, если бы так можно было писать:
580 # @new_commands = keys %frequency_of_command - @known_commands;
583 $result .= "<h3 id='day$last_day'>".$Day_Name[$last_wday]."</h3>";
584 for my $entry_class (sort keys %new_entries_of) {
585 my $table_caption = "Таблица ".$table_number++.".".$Day_Name[$last_wday]
586 .". Новые ".$new_entries_of{$entry_class};
587 my $new_commands_section = make_new_entries_table(
588 $table_caption,
589 $entry_class=~/[0-9]+\s+(.*)/,
590 \@known_commands);
591 }
592 @known_commands = keys %frequency_of_command;
593 $result .= $this_day_result;
594 }
596 push @toc, "<a href='#day$day'>".$Day_Name[$wday]."</a>\n";
597 $last_day=$day;
598 $last_wday=$wday;
599 $this_day_result = q();
600 }
601 else {
602 $this_day_result .= minutes_passed($seconds_since_last_command);
603 }
605 $this_day_result .= "<div class='command' id='command:".$cl->{"id"}."' >\n";
607 # CONSOLE CHANGE
608 if ($cl->{"tty"} && $last_tty ne $cl->{"tty"} && 0) {
609 my $tty = $cl->{"tty"};
610 $this_day_result .= "<div class='ttychange'>"
611 . $tty
612 ."</div>";
613 $last_tty=$cl->{"tty"};
614 }
616 # Session change
617 if ( $last_session ne $cl->{"local_session_id"}) {
618 my $tty = $cl->{"tty"};
619 $this_day_result .= "<div class='ttychange'><a href='?local_session_id=".$cl->{"local_session_id"}."'>"
620 . $Sessions{$cl->{"local_session_id"}}->{"tty"}
621 ."</a></div>";
622 $last_session=$cl->{"local_session_id"};
623 }
625 # TIME
626 if ($Config{"show_time"} =~ /^y/i) {
627 $this_day_result .= "<div class='time'>$hour:$min:$sec</div>"
628 }
630 # COMMAND
631 my $cline;
632 $prompt_hint = join ("&#10;", map("$_=$cl->{$_}", grep (!/^(output|diff)$/, sort(keys(%{$cl})))));
633 $cline = "<span title='$prompt_hint'>".$cl->{"prompt"}."</span>".$cl->{"cline"};
634 $cline =~ s/\n//;
636 if ($cl->{"hint"}) {
637 $cline = "<span title='$cl->{hint}' class='with_hint'>$cline</span>" ;
638 }
639 else {
640 $cline = "<span class='without_hint'>$cline</span>";
641 }
643 $this_day_result .= "<table cellpadding='0' cellspacing='0'><tr><td>\n<div class='cblock_$cl->{class}'>\n";
644 $this_day_result .= "<div class='cline'>\n" . $cline ; #cline
645 $this_day_result .= "<span title='Код завершения ".$cl->{"err"}."'>\n"
646 . "<img src='".$Config{frontend_ico_path}."/error.png'/>\n"
647 . "</span>\n" if $cl->{"err"};
648 $this_day_result .= "</div>\n"; #cline
650 # OUTPUT
651 my $last_command = $cl->{"last_command"};
652 if (!(
653 $Config{"suppress_editors"} =~ /^y/i && grep ($_ eq $last_command, @{$Config{"editors"}}) ||
654 $Config{"suppress_pagers"} =~ /^y/i && grep ($_ eq $last_command, @{$Config{"pagers"}}) ||
655 $Config{"suppress_terminal"}=~ /^y/i && grep ($_ eq $last_command, @{$Config{"terminal"}})
656 )) {
657 $this_day_result .= "<pre class='output'>\n" . $cl->{short_output} . "</pre>\n";
658 }
660 # DIFF
661 $this_day_result .= "<pre class='diff'>".$cl->{"diff"}."</pre>"
662 if ( $Config{"show_diffs"} =~ /^y/i && $cl->{"diff"});
663 # SHOT
664 $this_day_result .= "<img src='"
665 .$Config{l3shot_path}
666 .$cl->{"screenshot"}
667 .$Config{l3shot_suffix}
668 ."' alt ='screenshot id ".$cl->{"screenshot"}
669 ."'/>"
670 if ( $Config{"show_screenshots"} =~ /^y/i && $cl->{"screenshot"});
672 #NOTES
673 if ( $Config{"show_notes"} =~ /^y/i && $cl->{"note"}) {
674 my $note=$cl->{"note"};
675 $note =~ s/\n/<br\/>\n/msg;
676 if (not $note =~ s@(http:[a-zA-Z.0-9/_?%-]*)@<a href='$1'>$1</a>@g) {
677 $note =~ s@(www\.[a-zA-Z.0-9/_?%-]*)@<a href='$1'>$1</a>@g;
678 };
679 $this_day_result .= "<div class='note'>";
680 $this_day_result .= "<div class='note_title'>".$cl->{note_title}."</div>" if $cl->{note_title};
681 $this_day_result .= "<div class='note_text'>".$note."</div>";
682 $this_day_result .= "</div>\n";
683 }
685 # Вывод очередной команды окончен
686 $this_day_result .= "</div>\n"; # cblock
687 $this_day_result .= "</td></tr></table>\n"
688 . "</div>\n"; # command
689 }
690 last: {
691 $result .= "<h3 id='day$last_day'>".$Day_Name[$last_wday]."</h3>";
693 for my $entry_class (keys %new_entries_of) {
694 my $table_caption = "Таблица ".$table_number++.".".$Day_Name[$last_wday]
695 . ". Новые ".$new_entries_of{$entry_class};
696 my $new_commands_section = make_new_entries_table(
697 $table_caption,
698 $entry_class=~/[0-9]+\s+(.*)/,
699 \@known_commands);
700 }
701 @known_commands = keys %frequency_of_command;
702 $result .= $this_day_result;
703 }
705 return ($result, collapse_list (\@toc));
707 }
709 #############
710 # make_new_entries_table
711 #
712 # Напечатать таблицу неизвестных команд
713 #
714 # In: $_[0] table_caption
715 # $_[1] entries_class
716 # @_[2..] known_commands
717 # Out:
719 sub make_new_entries_table
720 {
721 my $table_caption;
722 my $entries_class = shift;
723 my @known_commands = @{$_[0]};
724 my $result = "";
726 my %count;
727 my @new_commands = ();
728 for my $c (keys %frequency_of_command, @known_commands) {
729 $count{$c}++
730 }
731 for my $c (keys %frequency_of_command) {
732 push @new_commands, $c if $count{$c} != 2;
733 }
735 my $new_commands_section;
736 if (@new_commands){
737 my $hint;
738 for my $c (reverse sort { $frequency_of_command{$a} <=> $frequency_of_command{$b} } @new_commands) {
739 $hint = make_comment($c);
740 next unless $hint;
741 my ($command, $hint) = $hint =~ m/(.*?) \s*- \s*(.*)/;
742 next unless $command =~ s/\($entries_class\)//i;
743 $new_commands_section .= "<tr><td valign='top'>$command</td><td>$hint</td></tr>";
744 }
745 }
746 if ($new_commands_section) {
747 $result .= "<table class='new_commands_table' width='700' cellspacing='0' cellpadding='0'>"
748 . "<tr class='new_commands_caption'>"
749 . "<td colspan='2' align='right'>$table_caption</td>"
750 . "</tr>"
751 . "<tr class='new_commands_header'>"
752 . "<td width=100>Команда</td><td width=600>Описание</td>"
753 . "</tr>"
754 . $new_commands_section
755 . "</table>"
756 }
757 return $result;
758 }
760 #############
761 # minutes_passed
762 #
763 #
764 #
765 # In: $_[0] seconds_since_last_command
766 # Out: "minutes passed" text
768 sub minutes_passed
769 {
770 my $seconds_since_last_command = shift;
771 my $result = "";
772 if ($seconds_since_last_command > 7200) {
773 my $hours_passed = int($seconds_since_last_command/3600);
774 my $passed_word = $hours_passed % 10 == 1 ? "прошла"
775 : "прошло";
776 my $hours_word = $hours_passed % 10 == 1 ? "часа":
777 "часов";
778 $result .= "<div class='much_time_passed'>"
779 . $passed_word." &gt;".$hours_passed." ".$hours_word
780 . "</div>\n";
781 }
782 elsif ($seconds_since_last_command > 600) {
783 my $minutes_passed = int($seconds_since_last_command/60);
786 my $passed_word = $minutes_passed % 100 > 10
787 && $minutes_passed % 100 < 20 ? "прошло"
788 : $minutes_passed % 10 == 1 ? "прошла"
789 : "прошло";
791 my $minutes_word = $minutes_passed % 100 > 10
792 && $minutes_passed % 100 < 20 ? "минут" :
793 $minutes_passed % 10 == 1 ? "минута":
794 $minutes_passed % 10 == 0 ? "минут" :
795 $minutes_passed % 10 > 4 ? "минут" :
796 "минуты";
798 if ($seconds_since_last_command < 1800) {
799 $result .= "<div class='time_passed'>"
800 . $passed_word." ".$minutes_passed." ".$minutes_word
801 . "</div>\n";
802 }
803 else {
804 $result .= "<div class='much_time_passed'>"
805 . $passed_word." ".$minutes_passed." ".$minutes_word
806 . "</div>\n";
807 }
808 }
809 return $result;
810 }
812 #############
813 # print_all_txt
814 #
815 # Вывести журнал в текстовом формате
816 #
817 # In: $_[0] output_filename
818 # Out:
820 sub print_all_txt
821 {
823 my $output_filename=$_[0];
824 my $note_number=0;
826 my $result = q();
827 my $this_day_resut = q();
829 my $cl;
830 my $last_tty="";
831 my $last_session="";
832 my $last_day=q();
833 my $last_wday=q();
834 my $in_range=0;
836 my $current_command=0;
838 my $cursor_position = 0;
841 if ($Config{filter}) {
842 # Инициализация фильтра
843 for (split /&/,$Config{filter}) {
844 my ($var, $val) = split /=/;
845 $filter{$var} = $val || "";
846 }
847 }
850 COMMAND_LINE:
851 for my $k (@Command_Lines_Index) {
853 my $cl=$Command_Lines[$Command_Lines_Index[$current_command++]];
854 next unless $cl;
857 # Пропускаем строки, которые противоречат фильтру
858 # Если у нас недостаточно информации о том, подходит строка под фильтр или нет,
859 # мы её выводим
861 for my $filter_key (keys %filter) {
862 next COMMAND_LINE
863 if defined($cl->{local_session_id})
864 && defined($Sessions{$cl->{local_session_id}}->{$filter_key})
865 && $Sessions{$cl->{local_session_id}}->{$filter_key} ne $filter{$filter_key};
866 }
868 # Пропускаем строки, выходящие за границу "signature",
869 # при условии, что границы указаны
870 # Пропускаем неправильные/прерванные/другие команды
871 if ($Config{"from"} && $cl->{"cline"} =~ /$Config{"signature"}\s*$Config{"from"}/) {
872 $in_range=1;
873 next;
874 }
875 if ($Config{"to"} && $cl->{"cline"} =~ /$Config{"signature"}\s*$Config{"to"}/) {
876 $in_range=0;
877 next;
878 }
879 next if ($Config{"from"} && $Config{"to"} && !$in_range)
880 || ($Config{"skip_empty"} =~ /^y/i && $cl->{"cline"} =~ /^\s*$/ )
881 || ($Config{"skip_wrong"} =~ /^y/i && $cl->{"err"} != 0)
882 || ($Config{"skip_interrupted"} =~ /^y/i && $cl->{"err"} == 130);
885 #
886 ##
887 ## Начинается собственно вывод
888 ##
889 #
891 ### Сначала обрабатываем границы разделов
892 ### Если тип команды "note", это граница
894 if ($cl->{class} eq "note") {
895 $this_day_result .= " === ".$cl->{note_title}." === \n" if $cl->{note_title};
896 $this_day_result .= $cl->{note}."\n";
897 next;
898 }
900 my ($sec,$min,$hour,$day,$mon,$year,$wday,$yday,$isdst) = localtime($cl->{time});
902 # Добавляем спереди 0 для удобочитаемости
903 $min = "0".$min if $min =~ /^.$/;
904 $hour = "0".$hour if $hour =~ /^.$/;
905 $sec = "0".$sec if $sec =~ /^.$/;
907 $class=$cl->{"class"};
909 # DAY CHANGE
910 if ( $last_day ne $day) {
911 if ($last_day) {
912 $result .= "== ".$Day_Name[$last_wday]." == \n";
913 $result .= $this_day_result;
914 }
915 $last_day = $day;
916 $last_wday = $wday;
917 $this_day_result = q();
918 }
920 # CONSOLE CHANGE
921 if ($cl->{"tty"} && $last_tty ne $cl->{"tty"} && 0) {
922 my $tty = $cl->{"tty"};
923 $this_day_result .= " #l3: ------- другая консоль ----\n";
924 $last_tty=$cl->{"tty"};
925 }
927 # Session change
928 if ( $last_session ne $cl->{"local_session_id"}) {
929 $this_day_result .= "# ------------------------------------------------------------"
930 . " l3: local_session_id=".$cl->{"local_session_id"}
931 . " ---------------------------------- \n";
932 $last_session=$cl->{"local_session_id"};
933 }
935 # TIME
936 my @nl_counter = split (/\n/, $result);
937 $cursor_position=length($result) - @nl_counter;
939 if ($Config{"show_time"} =~ /^y/i) {
940 $this_day_result .= "$hour:$min:$sec"
941 }
943 # COMMAND
944 $this_day_result .= " ".$cl->{"prompt"}.$cl->{"cline"}."\n";
945 if ($cl->{"err"}) {
946 $this_day_result .= " #l3: err=".$cl->{'err'}."\n";
947 }
949 # OUTPUT
950 my $last_command = $cl->{"last_command"};
951 if (!(
952 $Config{"suppress_editors"} =~ /^y/i && grep ($_ eq $last_command, @{$Config{"editors"}}) ||
953 $Config{"suppress_pagers"} =~ /^y/i && grep ($_ eq $last_command, @{$Config{"pagers"}}) ||
954 $Config{"suppress_terminal"}=~ /^y/i && grep ($_ eq $last_command, @{$Config{"terminal"}})
955 )) {
956 my $output = $cl->{short_output};
957 if ($output) {
958 $output =~ s/^/ |/mg;
959 }
960 $this_day_result .= $output;
961 }
963 # DIFF
964 if ( $Config{"show_diffs"} =~ /^y/i && $cl->{"diff"}) {
965 my $diff = $cl->{"diff"};
966 $diff =~ s/^/ |/mg;
967 $this_day_result .= $diff;
968 };
969 # SHOT
970 if ($Config{"show_screenshots"} =~ /^y/i && $cl->{"screenshot"}) {
971 $this_day_result .= " #l3: screenshot=".$cl->{'screenshot'}."\n";
972 }
974 #NOTES
975 if ( $Config{"show_notes"} =~ /^y/i && $cl->{"note"}) {
976 my $note=$cl->{"note"};
977 $note =~ s/\n/\n#^/msg;
978 $this_day_result .= "#^ == ".$cl->{note_title}." ==\n" if $cl->{note_title};
979 $this_day_result .= "#^ ".$note."\n";
980 }
982 }
983 last: {
984 $result .= "== ".$Day_Name[$last_wday]." == \n";
985 $result .= $this_day_result;
986 }
991 my $SetCursorPosition_JS = <<JS;
992 function setCursorPosition(oInput,oStart,oEnd) {
993 oInput.focus();
994 if( oInput.setSelectionRange ) {
995 oInput.setSelectionRange(oStart,oEnd);
996 } else if( oInput.createTextRange ) {
997 var range = oInput.createTextRange();
998 range.collapse(true);
999 range.moveEnd('character',oEnd);
1000 range.moveStart('character',oStart);
1001 range.select();
1004 JS
1006 if ($output_filename eq "-") {
1007 print
1008 "<html>"
1009 ."<script>"
1010 .$SetCursorPosition_JS
1011 ."</script>"
1012 ."<body onLoad='setCursorPosition(document.all.mytextarea, $cursor_position, $cursor_position+10)'>"
1013 ."<textarea rows='30' cols='100' wrap='off' id='mytextarea'>$result</textarea>"
1014 ."</body>"
1015 ."</html>"
1018 else {
1019 open(OUT, ">", $output_filename)
1020 or die "Can't open $output_filename for writing\n";
1021 print OUT "<pre>$result</pre>";
1022 close(OUT);
1027 #############
1028 # print_all_html
1032 # In: $_[0] output_filename
1033 # Out:
1036 sub print_all_html
1038 my $output_filename=$_[0];
1040 my $result;
1041 my ($command_lines,$toc) = print_command_lines_html;
1042 my $files_section = print_files_html;
1044 $result = print_header_html($toc);
1047 # $result.= join " <br/>", keys %Sessions;
1048 # for my $sess (keys %Sessions) {
1049 # $result .= join " ", keys (%{$Sessions{$sess}});
1050 # $result .= "<br/>";
1051 # }
1053 $result.= "<h2 id='log'>Журнал</h2>" . $command_lines;
1054 $result.= "<h2 id='files'>Файлы</h2>" . $files_section if $files_section;
1055 $result.= "<h2 id='stat'>Статистика</h2>" . print_stat;
1056 $result.= "<h2 id='help'>Справка</h2>" . $Html_Help . "<br/>";
1057 $result.= "<h2 id='about'>О программе</h2>". $Html_About. "<br/>";
1058 $result.= print_footer_html;
1060 if ($output_filename eq "-") {
1061 print $result;
1063 else {
1064 open(OUT, ">", $output_filename)
1065 or die "Can't open $output_filename for writing\n";
1066 print OUT $result;
1067 close(OUT);
1071 #############
1072 # print_header_html
1076 # In: $_[0] Содержание
1077 # Out: Распечатанный заголовок
1079 sub print_header_html
1081 my $toc = $_[0];
1082 my $course_name = $Config{"course-name"};
1083 my $course_code = $Config{"course-code"};
1084 my $course_date = $Config{"course-date"};
1085 my $course_center = $Config{"course-center"};
1086 my $course_trainer = $Config{"course-trainer"};
1087 my $course_student = $Config{"course-student"};
1089 my $title = "Журнал лабораторных работ";
1090 $title .= " -- ".$course_student if $course_student;
1091 if ($course_date) {
1092 $title .= " -- ".$course_date;
1093 $title .= $course_code ? "/".$course_code
1094 : "";
1096 else {
1097 $title .= " -- ".$course_code if $course_code;
1100 # Управляющая форма
1101 my $control_form .= "<div class='visibility_form' title='Выберите какие элементы должны быть показаны в журнале'>"
1102 . "<span class='header'>Видимые элементы</span>"
1103 . "<span class='window_controls'><a href='' onclick='' title='свернуть форму управления'>_</a> <a href='' onclick='' title='закрыть форму управления'>x</a></span>"
1104 . "<div><form>\n";
1105 for my $element (sort keys %Elements_Visibility)
1107 my ($skip, @e) = split /\s+/, $element;
1108 my $showhide = join "", map { "ShowHide('$_');" } @e ;
1109 $control_form .= "<div><input type='checkbox' name='$e[0]' onclick=\"$showhide\" checked>".
1110 $Elements_Visibility{$element}.
1111 "</input></div>";
1113 $control_form .= "</form>\n"
1114 . "</div>\n";
1116 my $result;
1117 $result = <<HEADER;
1118 <html>
1119 <head>
1120 <meta content='text/html; charset=utf-8' http-equiv='Content-Type' />
1121 <link rel='stylesheet' href='$Config{frontend_css}' type='text/css'/>
1122 <title>$title</title>
1123 </head>
1124 <body>
1125 <script>
1126 $Html_JavaScript
1127 </script>
1129 <!-- vvv Tigra Hints vvv -->
1130 <script language="JavaScript" src="/tigra/hints.js"></script>
1131 <script language="JavaScript" src="/tigra/hints_cfg.js"></script>
1132 <style>
1133 /* a class for all Tigra Hints boxes, TD object */
1134 .hintsClass
1135 {text-align: center; font-family: Verdana, Arial, Helvetica; padding: 0px 0px 0px 0px;}
1136 /* this class is used by Tigra Hints wrappers */
1137 .row
1138 {background: white;}
1139 </style>
1140 <!-- ^^^ Tigra Hints ^^^ -->
1143 <h1 onmouseover="myHint.show('1')" onmouseout="myHint.hide()">Журнал лабораторных работ</h1>
1144 HEADER
1145 if ( $course_student
1146 || $course_trainer
1147 || $course_name
1148 || $course_code
1149 || $course_date
1150 || $course_center) {
1151 $result .= "<p>";
1152 $result .= "Выполнил $course_student<br/>" if $course_student;
1153 $result .= "Проверил $course_trainer <br/>" if $course_trainer;
1154 $result .= "Курс " if $course_name
1155 || $course_code
1156 || $course_date;
1157 $result .= "$course_name " if $course_name;
1158 $result .= "($course_code)" if $course_code;
1159 $result .= ", $course_date<br/>" if $course_date;
1160 $result .= "Учебный центр $course_center <br/>" if $course_center;
1161 $result .= "Фильтр ".join(" ", map("$filter{$_}=$_", keys %filter))."<br/>" if %filter;
1162 $result .= "</p>";
1165 $result .= <<HEADER;
1166 <table width='100%'>
1167 <tr>
1168 <td width='*'>
1170 <table border=0 id='toc' class='toc'>
1171 <tr>
1172 <td>
1173 <div class='toc_title'>Содержание</div>
1174 <ul>
1175 <li><a href='#log'>Журнал</a></li>
1176 <ul>$toc</ul>
1177 <li><a href='#files'>Файлы</a></li>
1178 <li><a href='#stat'>Статистика</a></li>
1179 <li><a href='#help'>Справка</a></li>
1180 <li><a href='#about'>О программе</a></li>
1181 </ul>
1182 </td>
1183 </tr>
1184 </table>
1186 </td>
1187 <td valign='top' width=200>$control_form</td>
1188 </tr>
1189 </table>
1190 HEADER
1192 return $result;
1196 #############
1197 # print_footer_html
1204 sub print_footer_html
1206 return "</body>\n</html>\n";
1212 #############
1213 # print_stat_html
1217 # In:
1218 # Out:
1220 sub print_stat_html
1222 %StatNames = (
1223 FirstCommand => "Время первой команды журнала",
1224 LastCommand => "Время последней команды журнала",
1225 TotalCommands => "Количество командных строк в журнале",
1226 ErrorsPercentage => "Процент команд с ненулевым кодом завершения, %",
1227 MistypesPercentage => "Процент синтаксически неверно набранных команд, %",
1228 TotalTime => "Суммарное время работы с терминалом <sup><font size='-2'>*</font></sup>, час",
1229 CommandsPerTime => "Количество командных строк в единицу времени, команда/мин",
1230 CommandsFrequency => "Частота использования команд",
1231 RareCommands => "Частота использования этих команд < 0.5%",
1232 );
1233 @StatOrder = (
1234 FirstCommand,
1235 LastCommand,
1236 TotalCommands,
1237 ErrorsPercentage,
1238 MistypesPercentage,
1239 TotalTime,
1240 CommandsPerTime,
1241 CommandsFrequency,
1242 RareCommands,
1243 );
1245 # Подготовка статистики к выводу
1246 # Некоторые значения пересчитываются!
1247 # Дальше их лучше уже не использовать!!!
1249 my %CommandsFrequency = %frequency_of_command;
1251 $Stat{TotalTime} ||= 0;
1252 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($Stat{FirstCommand} || 0);
1253 $Stat{FirstCommand} = sprintf "%02i:%02i:%02i %04i-%2i-%2i", $hour, $min, $sec, $year+1900, $mon+1, $mday;
1254 ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($Stat{LastCommand} || 0);
1255 $Stat{LastCommand} = sprintf "%02i:%02i:%02i %04i-%2i-%2i", $hour, $min, $sec, $year+1900, $mon+1, $mday;
1256 if ($Stat{TotalCommands}) {
1257 $Stat{ErrorsPercentage} = sprintf "%5.2f", $Stat{ErrorCommands}*100/$Stat{TotalCommands};
1258 $Stat{MistypesPercentage} = sprintf "%5.2f", $Stat{MistypedCommands}*100/$Stat{TotalCommands};
1260 $Stat{CommandsPerTime} = sprintf "%5.2f", $Stat{TotalCommands}*60/$Stat{TotalTime}
1261 if $Stat{TotalTime};
1262 $Stat{TotalTime} = sprintf "%5.2f", $Stat{TotalTime}/60/60;
1264 my $total_commands=0;
1265 for $command (keys %CommandsFrequency){
1266 $total_commands += $CommandsFrequency{$command};
1268 if ($total_commands) {
1269 for $command (reverse sort {$CommandsFrequency{$a} <=> $CommandsFrequency{$b}} keys %CommandsFrequency){
1270 my $command_html;
1271 my $percentage = sprintf "%5.2f",$CommandsFrequency{$command}*100/$total_commands;
1272 if ($percentage < 0.5) {
1273 my $hint = make_comment($command);
1274 $command_html = "$command";
1275 $command_html = "<span title='$hint' class='with_hint'>$command_html</span>" if $hint;
1276 $command_html = "<span class='without_hint'>$command_html</span>" if not $hint;
1277 my $command_html = "<tt>$command_html</tt>";
1278 $Stat{RareCommands} .= $command_html."<sub><font size='-2'>".$CommandsFrequency{$command}."</font></sub> , ";
1280 else {
1281 my $hint = make_comment($command);
1282 $command_html = "$command";
1283 $command_html = "<span title='$hint' class='with_hint'>$command_html</span>" if $hint;
1284 $command_html = "<span class='without_hint'>$command_html</span>" if not $hint;
1285 my $command_html = "<tt>$command_html</tt>";
1286 $percentage = sprintf "%5.2f",$percentage;
1287 $Stat{CommandsFrequency} .= "<tr><td>".$command_html."</td><td>".$CommandsFrequency{$command}."</td>".
1288 "<td>|".("="x int($CommandsFrequency{$command}*100/$total_commands))."| $percentage%</td></tr>";
1291 $Stat{CommandsFrequency} = "<table>".$Stat{CommandsFrequency}."</table>";
1292 $Stat{RareCommands} =~ s/, $// if $Stat{RareCommands};
1295 my $result = q();
1296 for my $stat (@StatOrder) {
1297 next unless $Stat{"$stat"};
1298 $result .= "<tr valign='top'><td width='300'>".$StatNames{"$stat"}."</td><td>".$Stat{"$stat"}."</td></tr>"
1300 $result = "<table>$result</table>"
1301 . "<font size='-2'>____<br/>*) Интервалы неактивности длительностью "
1302 . ($Config{stat_inactivity_interval}/60)
1303 . " минут и более не учитываются</font></br>";
1305 return $result;
1309 sub collapse_list($)
1311 my $res = "";
1312 for my $elem (@{$_[0]}) {
1313 if (ref $elem eq "ARRAY") {
1314 $res .= "<ul>".collapse_list($elem)."</ul>";
1316 else
1318 $res .= "<li>".$elem."</li>";
1321 return $res;
1325 sub print_files_html
1327 my $result = qq();
1328 my @toc;
1329 for my $file (sort keys %Files) {
1330 my $div_id = "file:$file";
1331 $div_id =~ s@/@_@g;
1332 push @toc, "<a href='#$div_id'>$file</a>";
1333 $result .= "<div class='filename' id='$div_id'>".$file."</div>\n"
1334 . "<div class='file_navigation'><a href='#command:".$Files{$file}->{source_command_id}."'>"."&gt;"."</a></div>"
1335 . "<div class='filedata'><pre>".$Files{$file}->{content}."</pre></div>";
1337 return "<div class='files_toc'>".collapse_list(\@toc)."</div>".$result;
1341 sub init_variables
1343 $Html_Help = <<HELP;
1344 Для того чтобы использовать LiLaLo, не нужно знать ничего особенного:
1345 всё происходит само собой.
1346 Однако, чтобы ведение и последующее использование журналов
1347 было как можно более эффективным, желательно иметь в виду следующее:
1348 <ol>
1349 <li><p>
1350 В журнал автоматически попадают все команды, данные в любом терминале системы.
1351 </p></li>
1352 <li><p>
1353 Для того чтобы убедиться, что журнал на текущем терминале ведётся,
1354 и команды записываются, дайте команду w.
1355 В поле WHAT, соответствующем текущему терминалу,
1356 должна быть указана программа script.
1357 </p></li>
1358 <li><p>
1359 Команды, при наборе которых были допущены синтаксические ошибки,
1360 выводятся перечёркнутым текстом:
1361 <table>
1362 <tr class='command'>
1363 <td class='script'>
1364 <pre class='_mistyped_cline'>
1365 \$ l s-l</pre>
1366 <pre class='_mistyped_output'>bash: l: command not found
1367 </pre>
1368 </td>
1369 </tr>
1370 </table>
1371 <br/>
1372 </p></li>
1373 <li><p>
1374 Если код завершения команды равен нулю,
1375 команда была выполнена без ошибок.
1376 Команды, код завершения которых отличен от нуля, выделяются цветом.
1377 <table>
1378 <tr class='command'>
1379 <td class='script'>
1380 <pre class='_wrong_cline'>
1381 \$ test 5 -lt 4</pre>
1382 </pre>
1383 </td>
1384 </tr>
1385 </table>
1386 Обратите внимание на то, что код завершения команды может быть отличен от нуля
1387 не только в тех случаях, когда команда была выполнена с ошибкой.
1388 Многие команды используют код завершения, например, для того чтобы показать результаты проверки
1389 <br/>
1390 </p></li>
1391 <li><p>
1392 Команды, ход выполнения которых был прерван пользователем, выделяются цветом.
1393 <table>
1394 <tr class='command'>
1395 <td class='script'>
1396 <pre class='_interrupted_cline'>
1397 \$ find / -name abc</pre>
1398 <pre class='interrupted_output'>find: /home/devi-orig/.gnome2: Keine Berechtigung
1399 find: /home/devi-orig/.gnome2_private: Keine Berechtigung
1400 find: /home/devi-orig/.nautilus/metafiles: Keine Berechtigung
1401 find: /home/devi-orig/.metacity: Keine Berechtigung
1402 find: /home/devi-orig/.inkscape: Keine Berechtigung
1403 ^C
1404 </pre>
1405 </td>
1406 </tr>
1407 </table>
1408 <br/>
1409 </p></li>
1410 <li><p>
1411 Команды, выполненные с привилегиями суперпользователя,
1412 выделяются слева красной чертой.
1413 <table>
1414 <tr class='command'>
1415 <td class='script'>
1416 <pre class='_root_cline'>
1417 # id</pre>
1418 <pre class='_root_output'>
1419 uid=0(root) gid=0(root) Gruppen=0(root)
1420 </pre>
1421 </td>
1422 </tr>
1423 </table>
1424 <br/>
1425 </p></li>
1426 <li><p>
1427 Изменения, внесённые в текстовый файл с помощью редактора,
1428 запоминаются и показываются в журнале в формате ed.
1429 Строки, начинающиеся символом "&lt;", удалены, а строки,
1430 начинающиеся символом "&gt;" -- добавлены.
1431 <table>
1432 <tr class='command'>
1433 <td class='script'>
1434 <pre class='cline'>
1435 \$ vi ~/.bashrc</pre>
1436 <table><tr><td width='5'/><td class='diff'><pre>2a3,5
1437 &gt; if [ -f /usr/local/etc/bash_completion ]; then
1438 &gt; . /usr/local/etc/bash_completion
1439 &gt; fi
1440 </pre></td></tr></table></td>
1441 </tr>
1442 </table>
1443 <br/>
1444 </p></li>
1445 <li><p>
1446 Для того чтобы изменить файл в соответствии с показанными в диффшоте
1447 изменениями, можно воспользоваться командой patch.
1448 Нужно скопировать изменения, запустить программу patch, указав в
1449 качестве её аргумента файл, к которому применяются изменения,
1450 и всавить скопированный текст:
1451 <table>
1452 <tr class='command'>
1453 <td class='script'>
1454 <pre class='cline'>
1455 \$ patch ~/.bashrc</pre>
1456 </td>
1457 </tr>
1458 </table>
1459 В данном случае изменения применяются к файлу ~/.bashrc
1460 </p></li>
1461 <li><p>
1462 Для того чтобы получить краткую справочную информацию о команде,
1463 нужно подвести к ней мышь. Во всплывающей подсказке появится краткое
1464 описание команды.
1465 </p>
1466 <p>
1467 Если справочная информация о команде есть,
1468 команда выделяется голубым фоном, например: <span class="with_hint" title="главный текстовый редактор Unix">vi</span>.
1469 Если справочная информация отсутствует,
1470 команда выделяется розовым фоном, например: <span class="without_hint">notepad.exe</span>.
1471 Справочная информация может отсутствовать в том случае,
1472 если (1) команда введена неверно; (2) если распознавание команды LiLaLo выполнено неверно;
1473 (3) если информация о команде неизвестна LiLaLo.
1474 Последнее возможно для редких команд.
1475 </p></li>
1476 <li><p>
1477 Большие, в особенности многострочные, всплывающие подсказки лучше
1478 всего показываются браузерами KDE Konqueror, Apple Safari и Microsoft Internet Explorer.
1479 В браузерах Mozilla и Firefox они отображаются не полностью,
1480 а вместо перевода строки выводится специальный символ.
1481 </p></li>
1482 <li><p>
1483 Время ввода команды, показанное в журнале, соответствует времени
1484 <i>начала ввода командной строки</i>, которое равно тому моменту,
1485 когда на терминале появилось приглашение интерпретатора
1486 </p></li>
1487 <li><p>
1488 Имя терминала, на котором была введена команда, показано в специальном блоке.
1489 Этот блок показывается только в том случае, если терминал
1490 текущей команды отличается от терминала предыдущей.
1491 </p></li>
1492 <li><p>
1493 Вывод не интересующих вас в настоящий момент элементов журнала,
1494 таких как время, имя терминала и других, можно отключить.
1495 Для этого нужно воспользоваться <a href='#visibility_form'>формой управления журналом</a>
1496 вверху страницы.
1497 </p></li>
1498 <li><p>
1499 Небольшие комментарии к командам можно вставлять прямо из командной строки.
1500 Комментарий вводится прямо в командную строку, после символов #^ или #v.
1501 Символы ^ и v показывают направление выбора команды, к которой относится комментарий:
1502 ^ - к предыдущей, v - к следующей.
1503 Например, если в командной строке было введено:
1504 <pre class='cline'>
1505 \$ whoami
1506 </pre>
1507 <pre class='output'>
1508 user
1509 </pre>
1510 <pre class='cline'>
1511 \$ #^ Интересно, кто я?
1512 </pre>
1513 в журнале это будет выглядеть так:
1515 <pre class='cline'>
1516 \$ whoami
1517 </pre>
1518 <pre class='output'>
1519 user
1520 </pre>
1521 <table class='note'><tr><td width='100%' class='note_text'>
1522 <tr> <td> Интересно, кто я?<br/> </td></tr></table>
1523 </p></li>
1524 <li><p>
1525 Если комментарий содержит несколько строк,
1526 его можно вставить в журнал следующим образом:
1527 <pre class='cline'>
1528 \$ whoami
1529 </pre>
1530 <pre class='output'>
1531 user
1532 </pre>
1533 <pre class='cline'>
1534 \$ cat > /dev/null #^ Интересно, кто я?
1535 </pre>
1536 <pre class='output'>
1537 Программа whoami выводит имя пользователя, под которым
1538 мы зарегистрировались в системе.
1540 Она не может ответить на вопрос о нашем назначении
1541 в этом мире.
1542 </pre>
1543 В журнале это будет выглядеть так:
1544 <table>
1545 <tr class='command'>
1546 <td class='script'>
1547 <pre class='cline'>
1548 \$ whoami</pre>
1549 <pre class='output'>user
1550 </pre>
1551 <table class='note'><tr><td class='note_title'>Интересно, кто я?</td></tr><tr><td width='100%' class='note_text'>
1552 Программа whoami выводит имя пользователя, под которым<br/>
1553 мы зарегистрировались в системе.<br/>
1554 <br/>
1555 Она не может ответить на вопрос о нашем назначении<br/>
1556 в этом мире.<br/>
1557 </td></tr></table>
1558 </td>
1559 </tr>
1560 </table>
1561 Для разделения нескольких абзацев между собой
1562 используйте символ "-", один в строке.
1563 <br/>
1564 </p></li>
1565 <li><p>
1566 Комментарии, не относящиеся непосредственно ни к какой из команд,
1567 добавляются точно таким же способом, только вместо симолов #^ или #v
1568 нужно использовать символы #=
1569 </p></li>
1571 <p><li>
1572 Содержимое файла может быть показано в журнале.
1573 Для этого его нужно вывести с помощью программы cat.
1574 Если вывод команды отметить симоволами #!,
1575 содержимое файла будет показано в журнале
1576 в специально отведённой для этого секции.
1577 </li></p>
1579 <p>
1580 <li>
1581 Для того чтобы вставить скриншот интересующего вас окна в журнал,
1582 нужно воспользоваться командой l3shot.
1583 После того как команда вызвана, нужно с помощью мыши выбрать окно, которое
1584 должно быть в журнале.
1585 </li>
1586 </p>
1588 <p>
1589 <li>
1590 Команды в журнале расположены в хронологическом порядке.
1591 Если две команды давались одна за другой, но на разных терминалах,
1592 в журнале они будут рядом, даже если они не имеют друг к другу никакого отношения.
1593 <pre>
1598 </pre>
1599 Группы команд, выполненных на разных терминалах, разделяются специальной линией.
1600 Под этой линией в правом углу показано имя терминала, на котором выполнялись команды.
1601 Для того чтобы посмотреть команды только одного сенса,
1602 нужно щёкнуть по этому названию.
1603 </li>
1604 </p>
1605 </ol>
1606 HELP
1608 $Html_About = <<ABOUT;
1609 <p>
1610 LiLaLo (L3) расшифровывается как Live Lab Log.<br/>
1611 Программа разработана для повышения эффективности обучения Unix/Linux-системам.<br/>
1612 (c) Игорь Чубин, 2004-2006<br/>
1613 </p>
1614 ABOUT
1615 $Html_About.='$Id$ </p>';
1617 $Html_JavaScript = <<JS;
1618 function getElementsByClassName(Class_Name)
1620 var Result=new Array();
1621 var All_Elements=document.all || document.getElementsByTagName('*');
1622 for (i=0; i<All_Elements.length; i++)
1623 if (All_Elements[i].className==Class_Name)
1624 Result.push(All_Elements[i]);
1625 return Result;
1627 function ShowHide (name)
1629 elements=getElementsByClassName(name);
1630 for(i=0; i<elements.length; i++)
1631 if (elements[i].style.display == "none")
1632 elements[i].style.display = "";
1633 else
1634 elements[i].style.display = "none";
1635 //if (elements[i].style.visibility == "hidden")
1636 // elements[i].style.visibility = "visible";
1637 //else
1638 // elements[i].style.visibility = "hidden";
1640 function filter_by_output(text)
1643 var jjj=0;
1645 elements=getElementsByClassName('command');
1646 for(i=0; i<elements.length; i++) {
1647 subelems = elements[i].getElementsByTagName('pre');
1648 for(j=0; j<subelems.length; j++) {
1649 if (subelems[j].className = 'output') {
1650 var str = new String(subelems[j].nodeValue);
1651 if (jjj != 1) {
1652 alert(str);
1653 jjj=1;
1655 if (str.indexOf(text) >0)
1656 subelems[j].style.display = "none";
1657 else
1658 subelems[j].style.display = "";
1666 JS
1668 %Search_Machines = (
1669 "google" => { "query" => "http://www.google.com/search?q=" ,
1670 "icon" => "$Config{frontend_google_ico}" },
1671 "freebsd" => { "query" => "http://www.freebsd.org/cgi/man.cgi?query=",
1672 "icon" => "$Config{frontend_freebsd_ico}" },
1673 "linux" => { "query" => "http://man.he.net/?topic=",
1674 "icon" => "$Config{frontend_linux_ico}"},
1675 "opennet" => { "query" => "http://www.opennet.ru/search.shtml?words=",
1676 "icon" => "$Config{frontend_opennet_ico}"},
1677 "local" => { "query" => "http://www.freebsd.org/cgi/man.cgi?query=",
1678 "icon" => "$Config{frontend_local_ico}" },
1680 );
1682 %Elements_Visibility = (
1683 "0 new_commands_table" => "новые команды",
1684 "1 diff" => "редактор",
1685 "2 time" => "время",
1686 "3 ttychange" => "терминал",
1687 "4 wrong_output wrong_cline wrong_root_output wrong_root_cline"
1688 => "команды с ненулевым кодом завершения",
1689 "5 mistyped_output mistyped_cline mistyped_root_output mistyped_root_cline"
1690 => "неверно набранные команды",
1691 "6 interrupted_output interrupted_cline interrupted_root_output interrupted_root_cline"
1692 => "прерванные команды",
1693 "7 tab_completion_output tab_completion_cline"
1694 => "продолжение с помощью tab"
1695 );
1697 @Day_Name = qw/ Воскресенье Понедельник Вторник Среда Четверг Пятница Суббота /;
1698 @Month_Name = qw/ Январь Февраль Март Апрель Май Июнь Июль Август Сентябрь Октябрь Ноябрь Декабрь /;
1699 @Of_Month_Name = qw/ Января Февраля Марта Апреля Мая Июня Июля Августа Сентября Октября Ноября Декабря /;
1705 # Временно удалённый код
1706 # Возможно, он не понадобится уже никогда
1709 sub search_by
1711 my $sm = shift;
1712 my $topic = shift;
1713 $topic =~ s/ /+/;
1715 return "<a href='". $Search_Machines{$sm}->{"query"}."$topic'><img width='16' height='16' src='".
1716 $Search_Machines{$sm}->{"icon"}."' border='0'/></a>";