lilalo

view l3-frontend @ 109:3cd466f35ad6

* Добавлено разбиения журнала на блоки
* Оптимизирована генерация всплывающих подсказок
* В заголовке указывается дата
* Переделано взаимодействие с mywi: код mywi интегрирован в lilalo
* Изменён способ вывода таблицы, теперь она лушче показывается в Opera и IE
* Изменён формат diff'а, теперь diff -u
author igor
date Wed Feb 13 02:41:57 2008 +0200 (2008-02-13)
parents 54fbf2041159
children 99ea38e538c9
line source
1 #!/usr/bin/perl -w
3 use POSIX qw(strftime);
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 %Sessions;
14 our $debug_output=""; # Используйте эту переменную, если нужно передать отладочную информацию
16 our %filter;
17 our $filter_url;
18 sub init_filter;
20 our %Files;
22 # vvv Инициализация переменных выполняется процедурой init_variables
23 our @Day_Name;
24 our @Month_Name;
25 our @Of_Month_Name;
26 our %Search_Machines;
27 our %Elements_Visibility;
28 # ^^^
30 our $First_Command=$0;
31 our $Last_Command=40;
33 our %Stat;
34 our %frequency_of_command; # Сколько раз в журнале встречается какая команда
35 our $table_number=1;
36 our %tigra_hints;
38 my %mywi_cache_for; # Кэш для экономии обращений к mywi
40 sub count_frequency_of_commands;
41 sub make_comment;
42 sub make_new_entries_table;
43 sub load_command_lines_from_xml;
44 sub load_sessions_from_xml;
45 sub sort_command_lines;
46 sub process_command_lines;
47 sub init_variables;
48 sub main;
49 sub collapse_list($);
51 sub minutes_passed;
53 sub print_all_txt;
54 sub print_all_html;
55 sub print_edit_all_html;
56 sub print_command_lines_html;
57 sub print_command_lines_txt;
58 sub print_files_html;
59 sub print_stat_html;
60 sub print_header_html;
61 sub print_footer_html;
62 sub tigra_hints_generate;
64 #### mywi
65 #
66 sub mywi_init;
67 sub load_mywitxt;
68 sub mywi_process_query($);
69 #
70 sub add_to_log($$);
71 sub parse_query;
72 sub search_in_txt;
73 sub add_to_log($$);
74 sub mywi_guess($);
75 #
77 main();
79 sub main
80 {
81 $| = 1;
83 init_variables();
84 init_config();
85 $Config{frontend_ico_path}=$Config{frontend_css};
86 $Config{frontend_ico_path}=~s@/[^/]*$@@;
87 init_filter();
88 mywi_init();
90 load_command_lines_from_xml($Config{"backend_datafile"});
91 load_sessions_from_xml($Config{"backend_datafile"});
92 sort_command_lines;
93 process_command_lines;
94 if (defined($filter{action}) && $filter{action} eq "edit") {
95 print_edit_all_html($Config{"output"});
96 }
97 else {
98 print_all_html($Config{"output"});
99 }
100 }
102 sub init_filter
103 {
104 if ($Config{filter}) {
105 # Инициализация фильтра
106 for (split /&/,$Config{filter}) {
107 my ($var, $val) = split /=/;
108 $filter{$var} = $val || "";
109 }
110 }
111 $filter_url = join ("&", map("$_=$filter{$_}", keys %filter));
112 }
114 # extract_from_cline
116 # In: $what = commands | args
117 # Out: return ссылка на хэш, содержащий результаты разбора
118 # команда => позиция
120 # Разобрать командную строку $_[1] и возвратить хэш, содержащий
121 # номер первого появление команды в строке:
122 # команда => первая позиция
123 sub extract_from_cline
124 {
125 my $what = $_[0];
126 my $cline = $_[1];
127 my @lists = split /\;/, $cline;
130 my @command_lines = ();
131 for my $command_list (@lists) {
132 push(@command_lines, split(/\|/, $command_list));
133 }
135 my %position_of_command;
136 my %position_of_arg;
137 my $i=0;
138 for my $command_line (@command_lines) {
139 $command_line =~ s@^\s*@@;
140 $command_line =~ /\s*(\S+)\s*(.*)/;
141 if ($1 && $1 eq "sudo" ) {
142 $position_of_command{"$1"}=$i++;
143 $command_line =~ s/\s*sudo\s+//;
144 }
145 if ($command_line !~ m@^\s*\S*/etc/@) {
146 $command_line =~ s@^\s*\S+/@@;
147 }
149 $command_line =~ /\s*(\S+)\s*(.*)/;
150 my $command = $1;
151 my $args = $2;
152 if ($command && !defined $position_of_command{"$command"}) {
153 $position_of_command{"$command"}=$i++;
154 };
155 if ($args) {
156 my @args = split (/\s+/, $args);
157 for my $a (@args) {
158 $position_of_arg{"$a"}=$i++
159 if !defined $position_of_arg{"$a"};
160 };
161 }
162 }
164 if ($what eq "commands") {
165 return \%position_of_command;
166 } else {
167 return \%position_of_arg;
168 }
170 }
172 sub mywrap($)
173 {
174 return '<div class="t"><div class="b"><div class="l"><div class="r"><div class="bl"><div class="br"><div class="tl"><div class="tr">'.$_[0].
175 '</div></div></div></div></div></div></div></div>';
176 }
178 sub tigra_hints_generate
179 {
180 my $tigra_hints_items="";
181 for my $hint_id (keys %tigra_hints) {
182 $tigra_hints{$hint_id} =~ s@\n@<br/>@gs;
183 $tigra_hints{$hint_id} =~ s@ - @ — @gs;
184 $tigra_hints{$hint_id} =~ s@'@\\'@gs;
185 # $tigra_hints_items .= "'$hint_id' : mywrap('".$tigra_hints{$hint_id}."'),";
186 $tigra_hints_items .= "'$hint_id' : '".mywrap($tigra_hints{$hint_id})."',";
187 }
188 $tigra_hints_items =~ s/,$//;
189 return <<TIGRA;
191 var HINTS_CFG = {
192 'top' : 5, // a vertical offset of a hint from mouse pointer
193 'left' : 5, // a horizontal offset of a hint from mouse pointer
194 'css' : 'hintsClass', // a style class name for all hints, TD object
195 'show_delay' : 500, // a delay between object mouseover and hint appearing
196 'hide_delay' : 2000, // a delay between hint appearing and hint hiding
197 'wise' : true,
198 'follow' : true,
199 'z-index' : 0 // a z-index for all hint layers
200 },
202 HINTS_CFG_NEW = {
203 'wise' : true, // don't go off screen, don't overlap the object in the document
204 'margin' : 10, // minimum allowed distance between the hint and the window edge (negative values accepted)
205 'gap' : 20, // minimum allowed distance between the hint and the origin (negative values accepted)
206 'align' : 'bctl', // align of the hint and the origin (by first letters origin's top|middle|bottom left|center|right to hint's top|middle|bottom left|center|right)
207 'css' : 'hintsClass', // a style class name for all hints, applied to DIV element (see style section in the header of the document)
208 'show_delay' : 0, // a delay between initiating event (mouseover for example) and hint appearing
209 'hide_delay' : 200, // a delay between closing event (mouseout for example) and hint disappearing
210 'follow' : true, // hint follows the mouse as it moves
211 'z-index' : 100, // a z-index for all hint layers
212 'IEfix' : false, // fix IE problem with windowed controls visible through hints (activate if select boxes are visible through the hints)
213 'IEtrans' : ['blendTrans(DURATION=.3)', null], // [show transition, hide transition] - nice transition effects, only work in IE5+
214 'opacity' : 90 // opacity of the hint in %%
215 },
217 HINTS_ITEMS = {
218 $tigra_hints_items
219 };
220 var myHint = new THints (HINTS_CFG, HINTS_ITEMS);
223 function mywrap (s_) {
224 return '<div class="t"><div class="b"><div class="l"><div class="r"><div class="bl"><div class="br"><div class="tl"><div class="tr">'+s_+
225 '</div></div></div></div></div></div></div></div>';
227 }
228 TIGRA
229 $a=<<TIGRA;
230 TIGRA
231 }
234 sub count_frequency_of_commands
235 {
236 my $cline = $_[0];
237 my @commands = keys %{extract_from_cline("commands", $cline)};
238 for my $command (@commands) {
239 $frequency_of_command{$command}++;
240 }
241 }
243 sub make_comment
244 {
245 my $cline = $_[0];
246 #my $files = $_[1];
248 my @comments;
249 my @commands = keys %{extract_from_cline("commands", $cline)};
250 my @args = keys %{extract_from_cline("args", $cline)};
251 return if (!@commands && !@args);
252 #return "commands=".join(" ",@commands)."; files=".join(" ",@files);
254 # Commands
255 for my $command (@commands) {
256 $command =~ s/'//g;
257 #$frequency_of_command{$command}++;
258 if (!$Commands_Description{$command}) {
259 $mywi_cache_for{$command} ||= mywi_process_query($command) || "";
260 my $mywi = join ("\n", grep(/\([18]|sh|script\)/, split(/\n/, $mywi_cache_for{$command})));
261 $mywi =~ s/\s+/ /;
262 if ($mywi !~ /^\s*$/) {
263 $Commands_Description{$command} = $mywi;
264 }
265 else {
266 next;
267 }
268 }
270 push @comments, $Commands_Description{$command};
271 }
272 return join("&#10;\n", @comments);
274 # Files
275 for my $arg (@args) {
276 $arg =~ s/'//g;
277 if (!$Args_Description{$arg}) {
278 my $mywi;
279 $mywi = mywi_client ($arg);
280 $mywi = join ("\n", grep(/\([5]\)/, split(/\n/, $mywi)));
281 $mywi =~ s/\s+/ /;
282 if ($mywi !~ /^\s*$/) {
283 $Args_Description{$arg} = $mywi;
284 }
285 else {
286 next;
287 }
288 }
290 push @comments, $Args_Description{$arg};
291 }
293 }
295 =cut
296 Процедура load_command_lines_from_xml выполняет загрузку разобранного lab-скрипта
297 из XML-документа в переменную @Command_Lines
299 # In: $datafile имя файла
300 # Out: @CommandLines загруженные командные строки
302 Предупреждение!
303 Процедура не в состоянии обрабатывать XML-документ любой структуры.
304 В действительности файл cache из которого загружаются данные
305 просто напоминает XML с виду.
306 =cut
307 sub load_command_lines_from_xml
308 {
309 my $datafile = $_[0];
311 open (CLASS, $datafile)
312 or die "Can't open file with xml lablog ",$datafile,"\n";
313 local $/;
314 binmode CLASS, ":utf8";
315 $data = <CLASS>;
316 close(CLASS);
318 for $command ($data =~ m@<command>(.*?)</command>@sg) {
319 my %cl;
320 while ($command =~ m@<([^>]*?)>(.*?)</\1>@sg) {
321 $cl{$1} = $2;
322 }
323 push @Command_Lines, \%cl;
324 }
325 }
327 sub load_sessions_from_xml
328 {
329 my $datafile = $_[0];
331 open (CLASS, $datafile)
332 or die "Can't open file with xml lablog ",$datafile,"\n";
333 local $/;
334 binmode CLASS, ":utf8";
335 my $data = <CLASS>;
336 close(CLASS);
338 my $i=0;
339 for my $session ($data =~ m@<session>(.*?)</session>@msg) {
340 my %session_hash;
341 while ($session =~ m@<([^>]*?)>(.*?)</\1>@sg) {
342 $session_hash{$1} = $2;
343 }
344 $Sessions{$session_hash{local_session_id}} = \%session_hash;
345 }
346 }
349 # sort_command_lines
350 # In: @Command_Lines
351 # Out: @Command_Lies_Index
353 sub sort_command_lines
354 {
356 my @index;
357 for (my $i=0;$i<=$#Command_Lines;$i++) {
358 $index[$i]=$i;
359 }
361 @Command_Lines_Index = sort {
362 $Command_Lines[$index[$a]]->{"time"} <=> $Command_Lines[$index[$b]]->{"time"}
363 } @index;
365 }
367 ##################
368 # process_command_lines
369 #
370 # Обрабатываются командные строки @Command_Lines
371 # Для каждой строки определяется:
372 # class класс
373 # note комментарий
374 #
375 # In: @Command_Lines_Index
376 # In-Out: @Command_Lines
378 sub process_command_lines
379 {
382 my $current_command=0;
384 COMMAND_LINE_PROCESSING:
385 for my $i (@Command_Lines_Index) {
387 $current_command++;
388 next if $current_command < $Config{"start_from_command"};
389 last if $current_command > $Config{"start_from_command"} + $Config{"commands_to_show_at_a_go"};
391 my $cl = \$Command_Lines[$i];
393 next if !$cl;
395 for my $filter_key (keys %filter) {
396 next COMMAND_LINE_PROCESSING
397 if defined($$cl->{local_session_id})
398 && defined($Sessions{$$cl->{local_session_id}}->{$filter_key})
399 && $Sessions{$$cl->{local_session_id}}->{$filter_key} ne $filter{$filter_key};
400 }
402 $$cl->{id} = $$cl->{"time"};
404 $$cl->{err} ||=0;
406 # Класс команды
408 $$cl->{"class"} = $$cl->{"err"} eq 130 ? "interrupted"
409 : $$cl->{"err"} eq 127 ? "mistyped"
410 : $$cl->{"err"} ? "wrong"
411 : "normal";
413 if ($$cl->{"cline"} &&
414 $$cl->{"cline"} =~ /[^|`]\s*sudo/
415 || $$cl->{"uid"} eq 0) {
416 $$cl->{"class"}.="_root";
417 }
419 my $hint;
420 count_frequency_of_commands($$cl->{"cline"});
421 $hint = make_comment($$cl->{"cline"});
423 if ($hint) {
424 $$cl->{hint} = $hint;
425 }
426 $tigra_hints{$$cl->{"time"}} = $hint;
428 $$cl->{hint}="";
430 # Выводим <head_lines> верхних строк
431 # и <tail_lines> нижних строк,
432 # если эти параметры существуют
433 my $output="";
435 if ($$cl->{"last_command"} eq "cat" && !$$cl->{"err"} && !($$cl->{"cline"} =~ /</)) {
436 my $filename = $$cl->{"cline"};
437 $filename =~ s/.*\s+(\S+)\s*$/$1/;
438 $Files{$filename}->{"content"} = $$cl->{"output"};
439 $Files{$filename}->{"source_command_id"} = $$cl->{"id"}
440 }
441 my @lines = split '\n', $$cl->{"output"};
442 if ((
443 $Config{"head_lines"}
444 || $Config{"tail_lines"}
445 )
446 && $#lines > $Config{"head_lines"} + $Config{"tail_lines"} ) {
447 #
448 for (my $i=0; $i<= $#lines && $i < $Config{"head_lines"}; $i++) {
449 $output .= $lines[$i]."\n";
450 }
451 $output .= $Config{"skip_text"}."\n";
453 my $start_line=$#lines-$Config{"tail_lines"}+1;
454 for (my $i=$start_line; $i<= $#lines; $i++) {
455 $output .= $lines[$i]."\n";
456 }
457 }
458 else {
459 $output = $$cl->{"output"};
460 }
461 $$cl->{short_output} = $output;
463 #Обработка пометок
464 # Если несколько пометок (notes) идут подряд,
465 # они все объединяются
467 if ($$cl->{cline} =~ /l3shot/) {
468 if ($$cl->{output} =~ m@Screenshot is written to.*/(.*)\.xwd@) {
469 $$cl->{screenshot}="$1";
470 }
471 }
473 if ($$cl->{cline}=~ m@cat[^#]*#([\^=v])\s*(.*)@) {
475 my $note_operator = $1;
476 my $note_title = $2;
478 if ($note_operator eq "=") {
479 $$cl->{"class"} = "note";
480 $$cl->{"note"} = $$cl->{"output"};
481 $$cl->{"note_title"} = $2;
482 }
483 else {
484 my $j = $i;
485 if ($note_operator eq "^") {
486 $j--;
487 $j-- while ($j >=0 && (!$Command_Lines[$j] || $Command_Lines[$j]->{tty} ne $$cl->{tty}));
488 }
489 elsif ($note_operator eq "v") {
490 $j++;
491 $j++ while ($j <= @Command_Lines && (!$Command_Lines[$j] || $Command_Lines[$j]->{tty} ne $$cl->{tty}));
492 }
493 $Command_Lines[$j]->{note_title}=$note_title;
494 $Command_Lines[$j]->{note}.=$$cl->{output};
495 $$cl=0;
496 }
497 }
498 elsif ($$cl->{cline}=~ /#([\^=v])(.*)/) {
500 my $note_operator = $1;
501 my $note_text = $2;
503 if ($note_operator eq "=") {
504 $$cl->{"class"} = "note";
505 $$cl->{"note"} = $note_text;
506 }
507 else {
508 my $j=$i;
509 if ($note_operator eq "^") {
510 $j--;
511 $j-- while ($j >=0 && (!$Command_Lines[$j] || $Command_Lines[$j]->{tty} ne $$cl->{tty}));
512 }
513 elsif ($note_operator eq "v") {
514 $j++;
515 $j++ while ($j <= @Command_Lines && $Command_Lines[$j]->{tty} ne $$cl->{tty} || !$Command_Lines[$j]);
516 }
517 $Command_Lines[$j]->{note}.="$note_text\n";
518 $$cl=0;
519 }
520 }
521 if ($$cl->{"class"} eq "note") {
522 my $note_html = $$cl->{note};
523 $note_html = join ("\n", map ("<p>$_</p>", split (/-\n/, $note_html)));
524 $note_html =~ s@(http:[a-zA-Z.0-9/?\_%-]*)@<a href='$1'>$1</a>@g;
525 $note_html =~ s@(www\.[a-zA-Z.0-9/?\_%-]*)@<a href='$1'>$1</a>@g;
526 $$cl->{"note_html"} = $note_html;
527 }
528 }
530 }
533 =cut
534 Процедура print_command_lines выводит HTML-представление
535 разобранного lab-скрипта.
537 Разобранный lab-скрипт должен находиться в массиве @Command_Lines
538 =cut
540 sub print_command_lines_html
541 {
543 my @toc; # Оглавление
544 my $note_number=0;
546 my $result = q();
547 my $this_day_resut = q();
549 my $cl;
550 my $last_tty="";
551 my $last_session="";
552 my $last_day=q();
553 my $last_wday=q();
554 my $first_command_of_the_day_unix_time=q();
555 my $human_readable_time=q();
556 my $in_range=0;
558 my $current_command=0;
560 my @known_commands;
564 $Stat{LastCommand} ||= 0;
565 $Stat{TotalCommands} ||= 0;
566 $Stat{ErrorCommands} ||= 0;
567 $Stat{MistypedCommands} ||= 0;
569 my %new_entries_of = (
570 "1 1" => "программы пользователя",
571 "2 8" => "программы администратора",
572 "3 sh" => "команды интерпретатора",
573 "4 script"=> "скрипты",
574 );
576 COMMAND_LINE:
577 for my $k (@Command_Lines_Index) {
579 my $cl=$Command_Lines[$Command_Lines_Index[$current_command++]];
580 next unless $cl;
582 next if $current_command < $Config{"start_from_command"};
583 last if $current_command > $Config{"start_from_command"} + $Config{"commands_to_show_at_a_go"};
586 # Пропускаем команды, с одинаковым временем
587 # Это не совсем правильно.
588 # Возможно, что это команды, набираемые с помощью <completion>
589 # или запомненные с помощью <ctrl-c>
591 next if $Stat{LastCommand} == $cl->{time};
593 # Пропускаем строки, которые противоречат фильтру
594 # Если у нас недостаточно информации о том, подходит строка под фильтр или нет,
595 # мы её выводим
597 for my $filter_key (keys %filter) {
598 next COMMAND_LINE
599 if defined($cl->{local_session_id})
600 && defined($Sessions{$cl->{local_session_id}}->{$filter_key})
601 && $Sessions{$cl->{local_session_id}}->{$filter_key} ne $filter{$filter_key};
602 }
604 # Набираем статистику
605 # Хэш %Stat
607 $Stat{FirstCommand} = $cl->{time} unless $Stat{FirstCommand};
608 if ($cl->{time} - $Stat{LastCommand} < $Config{stat_inactivity_interval}) {
609 $Stat{TotalTime} += $cl->{time} - $Stat{LastCommand}
610 }
611 my $seconds_since_last_command = $cl->{time} - $Stat{LastCommand};
613 if ($Stat{LastCommand} > $cl->{time}) {
614 $result .= "Время идёт вспять<br/>";
615 };
616 $Stat{LastCommand} = $cl->{time};
617 $Stat{TotalCommands}++;
619 # Пропускаем строки, выходящие за границу "signature",
620 # при условии, что границы указаны
621 # Пропускаем неправильные/прерванные/другие команды
622 if ($Config{"from"} && $cl->{"cline"} =~ /$Config{"signature"}\s*$Config{"from"}/) {
623 $in_range=1;
624 next;
625 }
626 if ($Config{"to"} && $cl->{"cline"} =~ /$Config{"signature"}\s*$Config{"to"}/) {
627 $in_range=0;
628 next;
629 }
630 next if ($Config{"from"} && $Config{"to"} && !$in_range)
631 || ($Config{"skip_empty"} =~ /^y/i && $cl->{"cline"} =~ /^\s*$/ )
632 || ($Config{"skip_wrong"} =~ /^y/i && $cl->{"err"} != 0)
633 || ($Config{"skip_interrupted"} =~ /^y/i && $cl->{"err"} == 130);
638 #
639 ##
640 ## Начинается собственно вывод
641 ##
642 #
644 ### Сначала обрабатываем границы разделов
645 ### Если тип команды "note", это граница
647 if ($cl->{class} eq "note") {
648 $this_day_result .= "<tr><td colspan='6'>"
649 . "<h4 id='note$note_number'>".$cl->{note_title}."</h4>" if $cl->{note_title}
650 . "".$cl->{note_html}."<p/><p/></td></tr>";
652 if ($cl->{note_title}) {
653 push @{$toc[@toc]},"<a href='#note$note_number'>".$cl->{note_title}."</a>";
654 $note_number++;
655 }
656 next;
657 }
659 my ($sec,$min,$hour,$day,$mon,$year,$wday,$yday,$isdst) = localtime($cl->{time});
662 # Добавляем спереди 0 для удобочитаемости
663 $min = "0".$min if $min =~ /^.$/;
664 $hour = "0".$hour if $hour =~ /^.$/;
665 $sec = "0".$sec if $sec =~ /^.$/;
667 $class=$cl->{"class"};
668 $Stat{ErrorCommands}++ if $class =~ /wrong/;
669 $Stat{MistypedCommands}++ if $class =~ /mistype/;
671 # DAY CHANGE
672 if ( $last_day ne $day) {
673 $prev_unix_time=$first_command_of_the_day_unix_time;
674 $first_command_of_the_day_unix_time = $cl->{time};
675 $human_readable_time = strftime "%D", localtime($prev_unix_time);
676 if ($last_day) {
678 # Вычисляем разность множеств.
679 # Что-то вроде этого, если бы так можно было писать:
680 # @new_commands = keys %frequency_of_command - @known_commands;
683 # Выводим предыдущий день
685 $result .= "<h3 id='day_on_sec_$prev_unix_time'>".$Day_Name[$last_wday]." ($human_readable_time)</h3>";
686 for my $entry_class (sort keys %new_entries_of) {
687 my $table_caption = "Таблица ".$table_number++.".".$Day_Name[$last_wday]
688 .". Новые ".$new_entries_of{$entry_class};
689 my $new_commands_section = make_new_entries_table(
690 $table_caption,
691 $entry_class=~/[0-9]+\s+(.*)/,
692 \@known_commands);
693 }
694 @known_commands = keys %frequency_of_command;
695 $result .= $this_day_result;
696 }
698 # Добавляем текущий день в оглавление
700 $human_readable_time = strftime "%D", localtime($first_command_of_the_day_unix_time);
701 push @toc, "<a href='#day_on_sec_$first_command_of_the_day_unix_time'>".$Day_Name[$wday]." ($human_readable_time)</a>\n";
704 $last_day=$day;
705 $last_wday=$wday;
706 $this_day_result = q();
707 }
708 else {
709 $this_day_result .= minutes_passed($seconds_since_last_command);
710 }
712 $this_day_result .= "<div class='command' id='command:".$cl->{"id"}."' >\n";
714 # CONSOLE CHANGE
715 if ($cl->{"tty"} && $last_tty ne $cl->{"tty"} && 0) {
716 my $tty = $cl->{"tty"};
717 $this_day_result .= "<div class='ttychange'>"
718 . $tty
719 ."</div>";
720 $last_tty=$cl->{"tty"};
721 }
723 # Session change
724 if ( $last_session ne $cl->{"local_session_id"}) {
725 my $tty;
726 if (defined $Sessions{$cl->{"local_session_id"}}->{"tty"}) {
727 $this_day_result .= "<div class='ttychange'><a href='?local_session_id=".$cl->{"local_session_id"}."'>"
728 . $Sessions{$cl->{"local_session_id"}}->{"tty"}
729 ."</a></div>";
730 }
731 $last_session=$cl->{"local_session_id"};
732 }
734 # TIME
735 if ($Config{"show_time"} =~ /^y/i) {
736 $this_day_result .= "<div class='time'>$hour:$min:$sec</div>"
737 }
739 # COMMAND
740 my $cline;
741 $prompt_hint = join ("&#10;", map("$_=$cl->{$_}", grep (!/^(output|diff)$/, sort(keys(%{$cl})))));
742 $cline = "<span title='$prompt_hint'>".$cl->{"prompt"}."</span>".$cl->{"cline"};
743 $cline =~ s/\n//;
745 if ($cl->{"hint"}) {
746 $cline = "<span title='$cl->{hint}' class='with_hint'>$cline</span>" ;
747 }
748 else {
749 $cline = "<span class='without_hint'>$cline</span>";
750 }
752 $this_day_result .= "<DIV class='fixed_div'><table cellpadding='0' cellspacing='0'><tr><td>\n<div class='cblock_$cl->{class}'>\n";
753 $this_day_result .= "<div class='cline' onmouseover=\"myHint.show('".$cl->{time}."')\" onmouseout=\"myHint.hide()\">\n" . $cline ; #cline
754 $this_day_result .= "<span title='Код завершения ".$cl->{"err"}."'>\n"
755 . "<img src='".$Config{frontend_ico_path}."/error.png'/>\n"
756 . "</span>\n" if $cl->{"err"};
757 $this_day_result .= "</div>\n"; #cline
759 # OUTPUT
760 my $last_command = $cl->{"last_command"};
761 if (!(
762 $Config{"suppress_editors"} =~ /^y/i && grep ($_ eq $last_command, @{$Config{"editors"}}) ||
763 $Config{"suppress_pagers"} =~ /^y/i && grep ($_ eq $last_command, @{$Config{"pagers"}}) ||
764 $Config{"suppress_terminal"}=~ /^y/i && grep ($_ eq $last_command, @{$Config{"terminal"}})
765 )) {
766 $this_day_result .= "<pre class='output'>\n" . $cl->{short_output} . "</pre>\n";
767 }
769 # DIFF
770 $this_day_result .= "<pre class='diff'>".$cl->{"diff"}."</pre>"
771 if ( $Config{"show_diffs"} =~ /^y/i && $cl->{"diff"});
772 # SHOT
773 $this_day_result .= "<img src='"
774 .$Config{l3shot_path}
775 .$cl->{"screenshot"}
776 .$Config{l3shot_suffix}
777 ."' alt ='screenshot id ".$cl->{"screenshot"}
778 ."'/>"
779 if ( $Config{"show_screenshots"} =~ /^y/i && $cl->{"screenshot"});
781 #NOTES
782 if ( $Config{"show_notes"} =~ /^y/i && $cl->{"note"}) {
783 my $note=$cl->{"note"};
784 $note =~ s/\n/<br\/>\n/msg;
785 if (not $note =~ s@(http:[a-zA-Z.0-9/_?%-]*)@<a href='$1'>$1</a>@g) {
786 $note =~ s@(www\.[a-zA-Z.0-9/_?%-]*)@<a href='$1'>$1</a>@g;
787 };
788 $this_day_result .= "<div class='note'>";
789 $this_day_result .= "<div class='note_title'>".$cl->{note_title}."</div>" if $cl->{note_title};
790 $this_day_result .= "<div class='note_text'>".$note."</div>";
791 $this_day_result .= "</div>\n";
792 }
794 # Вывод очередной команды окончен
795 $this_day_result .= "</div>\n"; # cblock
796 $this_day_result .= "</td></tr></table></DIV>\n"
797 . "</div>\n"; # command
798 }
799 last: {
800 $prev_unix_time=$first_command_of_the_day_unix_time;
801 $first_command_of_the_day_unix_time = $cl->{time};
802 $human_readable_time = strftime "%D", localtime($prev_unix_time);
804 $result .= "<h3 id='day_on_sec_$prev_unix_time'>".$Day_Name[$last_wday]." ($human_readable_time)</h3>";
806 for my $entry_class (keys %new_entries_of) {
807 my $table_caption = "Таблица ".$table_number++.".".$Day_Name[$last_wday]
808 . ". Новые ".$new_entries_of{$entry_class};
809 my $new_commands_section = make_new_entries_table(
810 $table_caption,
811 $entry_class=~/[0-9]+\s+(.*)/,
812 \@known_commands);
813 }
814 @known_commands = keys %frequency_of_command;
815 $result .= $this_day_result;
816 }
818 return ($result, collapse_list (\@toc));
820 }
822 #############
823 # make_new_entries_table
824 #
825 # Напечатать таблицу неизвестных команд
826 #
827 # In: $_[0] table_caption
828 # $_[1] entries_class
829 # @_[2..] known_commands
830 # Out:
832 sub make_new_entries_table
833 {
834 my $table_caption;
835 my $entries_class = shift;
836 my @known_commands = @{$_[0]};
837 my $result = "";
839 my %count;
840 my @new_commands = ();
841 for my $c (keys %frequency_of_command, @known_commands) {
842 $count{$c}++
843 }
844 for my $c (keys %frequency_of_command) {
845 push @new_commands, $c if $count{$c} != 2;
846 }
848 my $new_commands_section;
849 if (@new_commands){
850 my $hint;
851 for my $c (reverse sort { $frequency_of_command{$a} <=> $frequency_of_command{$b} } @new_commands) {
852 $hint = make_comment($c);
853 next unless $hint;
854 my ($command, $hint) = $hint =~ m/(.*?) \s*- \s*(.*)/;
855 next unless $command =~ s/\($entries_class\)//i;
856 $new_commands_section .= "<tr><td valign='top'>$command</td><td>$hint</td></tr>";
857 }
858 }
859 if ($new_commands_section) {
860 $result .= "<table class='new_commands_table' width='700' cellspacing='0' cellpadding='0'>"
861 . "<tr class='new_commands_caption'>"
862 . "<td colspan='2' align='right'>$table_caption</td>"
863 . "</tr>"
864 . "<tr class='new_commands_header'>"
865 . "<td width=100>Команда</td><td width=600>Описание</td>"
866 . "</tr>"
867 . $new_commands_section
868 . "</table>"
869 }
870 return $result;
871 }
873 #############
874 # minutes_passed
875 #
876 #
877 #
878 # In: $_[0] seconds_since_last_command
879 # Out: "minutes passed" text
881 sub minutes_passed
882 {
883 my $seconds_since_last_command = shift;
884 my $result = "";
885 if ($seconds_since_last_command > 7200) {
886 my $hours_passed = int($seconds_since_last_command/3600);
887 my $passed_word = $hours_passed % 10 == 1 ? "прошла"
888 : "прошло";
889 my $hours_word = $hours_passed % 10 == 1 ? "часа":
890 "часов";
891 $result .= "<div class='much_time_passed'>"
892 . $passed_word." &gt;".$hours_passed." ".$hours_word
893 . "</div>\n";
894 }
895 elsif ($seconds_since_last_command > 600) {
896 my $minutes_passed = int($seconds_since_last_command/60);
899 my $passed_word = $minutes_passed % 100 > 10
900 && $minutes_passed % 100 < 20 ? "прошло"
901 : $minutes_passed % 10 == 1 ? "прошла"
902 : "прошло";
904 my $minutes_word = $minutes_passed % 100 > 10
905 && $minutes_passed % 100 < 20 ? "минут" :
906 $minutes_passed % 10 == 1 ? "минута":
907 $minutes_passed % 10 == 0 ? "минут" :
908 $minutes_passed % 10 > 4 ? "минут" :
909 "минуты";
911 if ($seconds_since_last_command < 1800) {
912 $result .= "<div class='time_passed'>"
913 . $passed_word." ".$minutes_passed." ".$minutes_word
914 . "</div>\n";
915 }
916 else {
917 $result .= "<div class='much_time_passed'>"
918 . $passed_word." ".$minutes_passed." ".$minutes_word
919 . "</div>\n";
920 }
921 }
922 return $result;
923 }
925 #############
926 # print_all_txt
927 #
928 # Вывести журнал в текстовом формате
929 #
930 # In: $_[0] output_filename
931 # Out:
933 sub print_command_lines_txt
934 {
936 my $output_filename=$_[0];
937 my $note_number=0;
939 my $result = q();
940 my $this_day_resut = q();
942 my $cl;
943 my $last_tty="";
944 my $last_session="";
945 my $last_day=q();
946 my $last_wday=q();
947 my $in_range=0;
949 my $current_command=0;
951 my $cursor_position = 0;
954 if ($Config{filter}) {
955 # Инициализация фильтра
956 for (split /&/,$Config{filter}) {
957 my ($var, $val) = split /=/;
958 $filter{$var} = $val || "";
959 }
960 }
963 COMMAND_LINE:
964 for my $k (@Command_Lines_Index) {
966 my $cl=$Command_Lines[$Command_Lines_Index[$current_command++]];
967 next unless $cl;
970 # Пропускаем строки, которые противоречат фильтру
971 # Если у нас недостаточно информации о том, подходит строка под фильтр или нет,
972 # мы её выводим
974 for my $filter_key (keys %filter) {
975 next COMMAND_LINE
976 if defined($cl->{local_session_id})
977 && defined($Sessions{$cl->{local_session_id}}->{$filter_key})
978 && $Sessions{$cl->{local_session_id}}->{$filter_key} ne $filter{$filter_key};
979 }
981 # Пропускаем строки, выходящие за границу "signature",
982 # при условии, что границы указаны
983 # Пропускаем неправильные/прерванные/другие команды
984 if ($Config{"from"} && $cl->{"cline"} =~ /$Config{"signature"}\s*$Config{"from"}/) {
985 $in_range=1;
986 next;
987 }
988 if ($Config{"to"} && $cl->{"cline"} =~ /$Config{"signature"}\s*$Config{"to"}/) {
989 $in_range=0;
990 next;
991 }
992 next if ($Config{"from"} && $Config{"to"} && !$in_range)
993 || ($Config{"skip_empty"} =~ /^y/i && $cl->{"cline"} =~ /^\s*$/ )
994 || ($Config{"skip_wrong"} =~ /^y/i && $cl->{"err"} != 0)
995 || ($Config{"skip_interrupted"} =~ /^y/i && $cl->{"err"} == 130);
998 #
999 ##
1000 ## Начинается собственно вывод
1001 ##
1004 ### Сначала обрабатываем границы разделов
1005 ### Если тип команды "note", это граница
1007 if ($cl->{class} eq "note") {
1008 $this_day_result .= " === ".$cl->{note_title}." === \n" if $cl->{note_title};
1009 $this_day_result .= $cl->{note}."\n";
1010 next;
1013 my ($sec,$min,$hour,$day,$mon,$year,$wday,$yday,$isdst) = localtime($cl->{time});
1015 # Добавляем спереди 0 для удобочитаемости
1016 $min = "0".$min if $min =~ /^.$/;
1017 $hour = "0".$hour if $hour =~ /^.$/;
1018 $sec = "0".$sec if $sec =~ /^.$/;
1020 $class=$cl->{"class"};
1022 # DAY CHANGE
1023 if ( $last_day ne $day) {
1024 if ($last_day) {
1025 $result .= "== ".$Day_Name[$last_wday]." == \n";
1026 $result .= $this_day_result;
1028 $last_day = $day;
1029 $last_wday = $wday;
1030 $this_day_result = q();
1033 # CONSOLE CHANGE
1034 if ($cl->{"tty"} && $last_tty ne $cl->{"tty"} && 0) {
1035 my $tty = $cl->{"tty"};
1036 $this_day_result .= " #l3: ------- другая консоль ----\n";
1037 $last_tty=$cl->{"tty"};
1040 # Session change
1041 if ( $last_session ne $cl->{"local_session_id"}) {
1042 $this_day_result .= "# ------------------------------------------------------------"
1043 . " l3: local_session_id=".$cl->{"local_session_id"}
1044 . " ---------------------------------- \n";
1045 $last_session=$cl->{"local_session_id"};
1048 # TIME
1049 my @nl_counter = split (/\n/, $result);
1050 $cursor_position=length($result) - @nl_counter;
1052 if ($Config{"show_time"} =~ /^y/i) {
1053 $this_day_result .= "$hour:$min:$sec"
1056 # COMMAND
1057 $this_day_result .= " ".$cl->{"prompt"}.$cl->{"cline"}."\n";
1058 if ($cl->{"err"}) {
1059 $this_day_result .= " #l3: err=".$cl->{'err'}."\n";
1062 # OUTPUT
1063 my $last_command = $cl->{"last_command"};
1064 if (!(
1065 $Config{"suppress_editors"} =~ /^y/i && grep ($_ eq $last_command, @{$Config{"editors"}}) ||
1066 $Config{"suppress_pagers"} =~ /^y/i && grep ($_ eq $last_command, @{$Config{"pagers"}}) ||
1067 $Config{"suppress_terminal"}=~ /^y/i && grep ($_ eq $last_command, @{$Config{"terminal"}})
1068 )) {
1069 my $output = $cl->{short_output};
1070 if ($output) {
1071 $output =~ s/^/ |/mg;
1073 $this_day_result .= $output;
1076 # DIFF
1077 if ( $Config{"show_diffs"} =~ /^y/i && $cl->{"diff"}) {
1078 my $diff = $cl->{"diff"};
1079 $diff =~ s/^/ |/mg;
1080 $this_day_result .= $diff;
1081 };
1082 # SHOT
1083 if ($Config{"show_screenshots"} =~ /^y/i && $cl->{"screenshot"}) {
1084 $this_day_result .= " #l3: screenshot=".$cl->{'screenshot'}."\n";
1087 #NOTES
1088 if ( $Config{"show_notes"} =~ /^y/i && $cl->{"note"}) {
1089 my $note=$cl->{"note"};
1090 $note =~ s/\n/\n#^/msg;
1091 $this_day_result .= "#^ == ".$cl->{note_title}." ==\n" if $cl->{note_title};
1092 $this_day_result .= "#^ ".$note."\n";
1096 last: {
1097 $result .= "== ".$Day_Name[$last_wday]." == \n";
1098 $result .= $this_day_result;
1101 return $result;
1107 #############
1108 # print_edit_all_html
1110 # Вывести страницу с текстовым представлением журнала для редактирования
1112 # In: $_[0] output_filename
1113 # Out:
1115 sub print_edit_all_html
1117 my $output_filename= shift;
1118 my $result;
1119 my $cursor_position = 0;
1121 $result = print_command_lines_txt;
1122 my $title = ">Журнал лабораторных работ. Правка";
1124 $result =
1125 "<html>"
1126 ."<head>"
1127 ."<meta content='text/html; charset=utf-8' http-equiv='Content-Type' />"
1128 ."<link rel='stylesheet' href='$Config{frontend_css}' type='text/css'/>"
1129 ."<title>$title</title>"
1130 ."</head>"
1131 ."<script>"
1132 .$SetCursorPosition_JS
1133 ."</script>"
1134 ."<body onLoad='setCursorPosition(document.all.mytextarea, $cursor_position, $cursor_position+10)'>"
1135 ."<h1>Журнал лабораторных работ. Правка</h1>"
1136 ."<form>"
1137 ."<textarea rows='30' cols='100' wrap='off' id='mytextarea'>$result</textarea>"
1138 ."<br/><input type='submit' value='Сохранить' label='label'/>"
1139 ."</form>"
1140 ."<p>Внимательно правим, потом сохраняем</p>"
1141 ."<p>Строки, начинающиеся символами #l3: можно трогать, только если точно знаешь, что делаешь</p>"
1142 ."</body>"
1143 ."</html>";
1145 if ($output_filename eq "-") {
1146 print $result;
1148 else {
1149 open(OUT, ">", $output_filename)
1150 or die "Can't open $output_filename for writing\n";
1151 binmode ":utf8";
1152 print OUT "$result";
1153 close(OUT);
1157 #############
1158 # print_all_txt
1160 # Вывести страницу с текстовым представлением журнала для редактирования
1162 # In: $_[0] output_filename
1163 # Out:
1165 sub print_all_txt
1167 my $result;
1169 $result = print_command_lines_txt;
1171 $result =~ s/&gt;/>/g;
1172 $result =~ s/&lt;/</g;
1173 $result =~ s/&amp;/&/g;
1175 if ($output_filename eq "-") {
1176 print $result;
1178 else {
1179 open(OUT, ">:utf8", $output_filename)
1180 or die "Can't open $output_filename for writing\n";
1181 print OUT "$result";
1182 close(OUT);
1187 #############
1188 # print_all_html
1192 # In: $_[0] output_filename
1193 # Out:
1196 sub print_all_html
1198 my $output_filename=$_[0];
1200 my $result;
1201 my ($command_lines,$toc) = print_command_lines_html;
1202 my $files_section = print_files_html;
1204 $result = $debug_output;
1205 $result .= print_header_html($toc);
1208 # $result.= join " <br/>", keys %Sessions;
1209 # for my $sess (keys %Sessions) {
1210 # $result .= join " ", keys (%{$Sessions{$sess}});
1211 # $result .= "<br/>";
1212 # }
1214 $result.= "<h2 id='log'>Журнал</h2>" . $command_lines;
1215 $result.= "<h2 id='files'>Файлы</h2>" . $files_section if $files_section;
1216 $result.= "<h2 id='stat'>Статистика</h2>" . print_stat_html;
1217 $result.= "<h2 id='help'>Справка</h2>" . $Html_Help . "<br/>";
1218 $result.= "<h2 id='about'>О программе</h2>". $Html_About. "<br/>";
1219 $result.= print_footer_html;
1221 if ($output_filename eq "-") {
1222 binmode STDOUT, ":utf8";
1223 print $result;
1225 else {
1226 open(OUT, ">:utf8", $output_filename)
1227 or die "Can't open $output_filename for writing\n";
1228 print OUT $result;
1229 close(OUT);
1233 #############
1234 # print_header_html
1238 # In: $_[0] Содержание
1239 # Out: Распечатанный заголовок
1241 sub print_header_html
1243 my $toc = $_[0];
1244 my $course_name = $Config{"course-name"};
1245 my $course_code = $Config{"course-code"};
1246 my $course_date = $Config{"course-date"};
1247 my $course_center = $Config{"course-center"};
1248 my $course_trainer = $Config{"course-trainer"};
1249 my $course_student = $Config{"course-student"};
1251 my $title = "Журнал лабораторных работ";
1252 $title .= " -- ".$course_student if $course_student;
1253 if ($course_date) {
1254 $title .= " -- ".$course_date;
1255 $title .= $course_code ? "/".$course_code
1256 : "";
1258 else {
1259 $title .= " -- ".$course_code if $course_code;
1262 # Управляющая форма
1263 my $control_form .= "<div class='visibility_form' title='Выберите какие элементы должны быть показаны в журнале'>"
1264 . "<span class='header'>Видимые элементы</span>"
1265 . "<span class='window_controls'><a href='' onclick='' title='свернуть форму управления'>_</a> <a href='' onclick='' title='закрыть форму управления'>x</a></span>"
1266 . "<div><form>\n";
1267 for my $element (sort keys %Elements_Visibility)
1269 my ($skip, @e) = split /\s+/, $element;
1270 my $showhide = join "", map { "ShowHide('$_');" } @e ;
1271 $control_form .= "<div><input type='checkbox' name='$e[0]' onclick=\"$showhide\" checked>".
1272 $Elements_Visibility{$element}.
1273 "</input></div>";
1275 $control_form .= "</form>\n"
1276 . "</div>\n";
1279 # Управляющая форма отключена
1280 # Она слишком сильно мешает, нужно что-то переделать
1281 $control_form = "";
1283 my $tigra_hints_array=tigra_hints_generate;
1285 my $result;
1286 $result = <<HEADER;
1287 <html>
1288 <head>
1289 <meta content='text/html; charset=utf-8' http-equiv='Content-Type' />
1290 <link rel='stylesheet' href='$Config{frontend_css}' type='text/css'/>
1291 <title>$title</title>
1292 </head>
1293 <body>
1294 <!--<script>
1295 $Html_JavaScript
1296 </script>-->
1298 <!-- vvv Tigra Hints vvv -->
1299 <script language="JavaScript" src="/tigra/hints.js"></script>
1300 <!--<script language="JavaScript" src="/tigra/hints_cfg.js"></script>-->
1301 <script>$tigra_hints_array</script>
1302 <style>
1303 /* a class for all Tigra Hints boxes, TD object */
1304 .hintsClass
1305 {text-align: left; font-size:80%; font-family: Verdana, Arial, Helvetica; background-color:#ffffee; padding: 0px 0px 0px 0px;}
1306 /* this class is used by Tigra Hints wrappers */
1307 .row
1308 {background: white;}
1311 .bl2 {border: 1px solid #e68200; background:url(/tigra/block/bl2.gif) 0 100% no-repeat; text-align:left}
1312 .bl {background:url(/tigra/block/bl2.gif) 0 100% no-repeat; text-align:left}
1313 .br {background:url(/tigra/block/br2.gif) 100% 100% no-repeat}
1314 .tl {background:url(/tigra/block/tl2.gif) 0 0 no-repeat}
1315 .tr {background:url(/tigra/block/tr2.gif) 100% 0 no-repeat; padding:10px}
1316 .tr2 {background:url(/tigra/block/tr2.gif) 100% 0 no-repeat}
1317 .t {background:url(/tigra/block/dot2.gif) 0 0 repeat-x}
1318 .b {background:url(/tigra/block/dot2.gif) 0 100% repeat-x}
1319 .l {background:url(/tigra/block/dot2.gif) 0 0 repeat-y}
1320 .r {background:url(/tigra/block/dot2.gif) 100% 0 repeat-y}
1323 </style>
1324 <!-- ^^^ Tigra Hints ^^^ -->
1326 <!--
1327 .bl2 {border: 1px solid #e68200; background:url(/tigra/block/bl2.gif) 0 100% no-repeat; width:20em; text-align:center}
1328 .bl {background:url(/tigra/block/bl2.gif) 0 100% no-repeat; width:20em; text-align:center}
1329 .br {background:url(/tigra/block/br2.gif) 100% 100% no-repeat}
1330 .tl {background:url(/tigra/block/tl2.gif) 0 0 no-repeat}
1331 .tr {background:url(/tigra/block/tr2.gif) 100% 0 no-repeat; padding:10px}
1332 .tr2 {background:url(/tigra/block/tr2.gif) 100% 0 no-repeat}
1333 .t {background:url(/tigra/block/dot2.gif) 0 0 repeat-x; width:20em}
1334 .b {background:url(/tigra/block/dot2.gif) 0 100% repeat-x}
1335 .l {background:url(/tigra/block/dot2.gif) 0 0 repeat-y}
1336 .r {background:url(/tigra/block/dot2.gif) 100% 0 repeat-y}
1337 -->
1340 <div class='edit_link'>
1341 [ <a href='?action=edit&$filter_url'>править</a> ]
1342 </div>
1343 <h1 onmouseover="myHint.show('1')" onmouseout="myHint.hide()" class='lined_header'>Журнал лабораторных работ</h1>
1344 HEADER
1345 if ( $course_student
1346 || $course_trainer
1347 || $course_name
1348 || $course_code
1349 || $course_date
1350 || $course_center) {
1351 $result .= "<p>";
1352 $result .= "Выполнил $course_student<br/>" if $course_student;
1353 $result .= "Проверил $course_trainer <br/>" if $course_trainer;
1354 $result .= "Курс " if $course_name
1355 || $course_code
1356 || $course_date;
1357 $result .= "$course_name " if $course_name;
1358 $result .= "($course_code)" if $course_code;
1359 $result .= ", $course_date<br/>" if $course_date;
1360 $result .= "Учебный центр $course_center <br/>" if $course_center;
1361 $result .= "Фильтр ".join(" ", map("$filter{$_}=$_", keys %filter))."<br/>" if %filter;
1362 $result .= "</p>";
1365 $result .= <<HEADER;
1366 <table width='100%'>
1367 <tr>
1368 <td width='*'>
1370 <table border=0 id='toc' class='toc'>
1371 <tr>
1372 <td>
1373 <div class='toc_title'>Содержание</div>
1374 <ul>
1375 <li><a href='#log'>Журнал</a></li>
1376 <ul>$toc</ul>
1377 <li><a href='#files'>Файлы</a></li>
1378 <li><a href='#stat'>Статистика</a></li>
1379 <li><a href='#help'>Справка</a></li>
1380 <li><a href='#about'>О программе</a></li>
1381 </ul>
1382 </td>
1383 </tr>
1384 </table>
1386 </td>
1387 <td valign='top' width=200>$control_form</td>
1388 </tr>
1389 </table>
1390 HEADER
1392 return $result;
1396 #############
1397 # print_footer_html
1404 sub print_footer_html
1406 return "</body>\n</html>\n";
1412 #############
1413 # print_stat_html
1417 # In:
1418 # Out:
1420 sub print_stat_html
1422 %StatNames = (
1423 FirstCommand => "Время первой команды журнала",
1424 LastCommand => "Время последней команды журнала",
1425 TotalCommands => "Количество командных строк в журнале",
1426 ErrorsPercentage => "Процент команд с ненулевым кодом завершения, %",
1427 MistypesPercentage => "Процент синтаксически неверно набранных команд, %",
1428 TotalTime => "Суммарное время работы с терминалом <sup><font size='-2'>*</font></sup>, час",
1429 CommandsPerTime => "Количество командных строк в единицу времени, команда/мин",
1430 CommandsFrequency => "Частота использования команд",
1431 RareCommands => "Частота использования этих команд < 0.5%",
1432 );
1433 @StatOrder = (
1434 FirstCommand,
1435 LastCommand,
1436 TotalCommands,
1437 ErrorsPercentage,
1438 MistypesPercentage,
1439 TotalTime,
1440 CommandsPerTime,
1441 CommandsFrequency,
1442 RareCommands,
1443 );
1445 # Подготовка статистики к выводу
1446 # Некоторые значения пересчитываются!
1447 # Дальше их лучше уже не использовать!!!
1449 my %CommandsFrequency = %frequency_of_command;
1451 $Stat{TotalTime} ||= 0;
1452 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($Stat{FirstCommand} || 0);
1453 $Stat{FirstCommand} = sprintf "%02i:%02i:%02i %04i-%2i-%2i", $hour, $min, $sec, $year+1900, $mon+1, $mday;
1454 ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($Stat{LastCommand} || 0);
1455 $Stat{LastCommand} = sprintf "%02i:%02i:%02i %04i-%2i-%2i", $hour, $min, $sec, $year+1900, $mon+1, $mday;
1456 if ($Stat{TotalCommands}) {
1457 $Stat{ErrorsPercentage} = sprintf "%5.2f", $Stat{ErrorCommands}*100/$Stat{TotalCommands};
1458 $Stat{MistypesPercentage} = sprintf "%5.2f", $Stat{MistypedCommands}*100/$Stat{TotalCommands};
1460 $Stat{CommandsPerTime} = sprintf "%5.2f", $Stat{TotalCommands}*60/$Stat{TotalTime}
1461 if $Stat{TotalTime};
1462 $Stat{TotalTime} = sprintf "%5.2f", $Stat{TotalTime}/60/60;
1464 my $total_commands=0;
1465 for $command (keys %CommandsFrequency){
1466 $total_commands += $CommandsFrequency{$command};
1468 if ($total_commands) {
1469 for $command (reverse sort {$CommandsFrequency{$a} <=> $CommandsFrequency{$b}} keys %CommandsFrequency){
1470 my $command_html;
1471 my $percentage = sprintf "%5.2f",$CommandsFrequency{$command}*100/$total_commands;
1472 if ($percentage < 0.5) {
1473 my $hint = make_comment($command);
1474 $command_html = "$command";
1475 $command_html = "<span title='$hint' class='with_hint'>$command_html</span>" if $hint;
1476 $command_html = "<span class='without_hint'>$command_html</span>" if not $hint;
1477 my $command_html = "<tt>$command_html</tt>";
1478 $Stat{RareCommands} .= $command_html."<sub><font size='-2'>".$CommandsFrequency{$command}."</font></sub> , ";
1480 else {
1481 my $hint = make_comment($command);
1482 $command_html = "$command";
1483 $command_html = "<span title='$hint' class='with_hint'>$command_html</span>" if $hint;
1484 $command_html = "<span class='without_hint'>$command_html</span>" if not $hint;
1485 my $command_html = "<tt>$command_html</tt>";
1486 $percentage = sprintf "%5.2f",$percentage;
1487 $Stat{CommandsFrequency} .= "<tr><td>".$command_html."</td><td>".$CommandsFrequency{$command}."</td>".
1488 "<td>|".("="x int($CommandsFrequency{$command}*100/$total_commands))."| $percentage%</td></tr>";
1491 $Stat{CommandsFrequency} = "<table>".$Stat{CommandsFrequency}."</table>";
1492 $Stat{RareCommands} =~ s/, $// if $Stat{RareCommands};
1495 my $result = q();
1496 for my $stat (@StatOrder) {
1497 next unless $Stat{"$stat"};
1498 $result .= "<tr valign='top'><td width='300'>".$StatNames{"$stat"}."</td><td>".$Stat{"$stat"}."</td></tr>"
1500 $result = "<table>$result</table>"
1501 . "<font size='-2'>____<br/>*) Интервалы неактивности длительностью "
1502 . ($Config{stat_inactivity_interval}/60)
1503 . " минут и более не учитываются</font></br>";
1505 return $result;
1509 sub collapse_list($)
1511 my $res = "";
1512 for my $elem (@{$_[0]}) {
1513 if (ref $elem eq "ARRAY") {
1514 $res .= "<ul>".collapse_list($elem)."</ul>";
1516 else
1518 $res .= "<li>".$elem."</li>";
1521 return $res;
1525 sub print_files_html
1527 my $result = qq();
1528 my @toc;
1529 for my $file (sort keys %Files) {
1530 my $div_id = "file:$file";
1531 $div_id =~ s@/@_@g;
1532 push @toc, "<a href='#$div_id'>$file</a>";
1533 $result .= "<div class='filename' id='$div_id'>".$file."</div>\n"
1534 . "<div class='file_navigation'><a href='#command:".$Files{$file}->{source_command_id}."'>"."&gt;"."</a></div>"
1535 . "<div class='filedata'><pre>".$Files{$file}->{content}."</pre></div>";
1537 if ($result) {
1538 return "<div class='files_toc'>".collapse_list(\@toc)."</div>".$result;
1540 else {
1541 return "";
1546 sub init_variables
1548 $Html_Help = <<HELP;
1549 Для того чтобы использовать LiLaLo, не нужно знать ничего особенного:
1550 всё происходит само собой.
1551 Однако, чтобы ведение и последующее использование журналов
1552 было как можно более эффективным, желательно иметь в виду следующее:
1553 <ol>
1554 <li><p>
1555 В журнал автоматически попадают все команды, данные в любом терминале системы.
1556 </p></li>
1557 <li><p>
1558 Для того чтобы убедиться, что журнал на текущем терминале ведётся,
1559 и команды записываются, дайте команду w.
1560 В поле WHAT, соответствующем текущему терминалу,
1561 должна быть указана программа script.
1562 </p></li>
1563 <li><p>
1564 Команды, при наборе которых были допущены синтаксические ошибки,
1565 выводятся перечёркнутым текстом:
1566 <table>
1567 <tr class='command'>
1568 <td class='script'>
1569 <pre class='_mistyped_cline'>
1570 \$ l s-l</pre>
1571 <pre class='_mistyped_output'>bash: l: command not found
1572 </pre>
1573 </td>
1574 </tr>
1575 </table>
1576 <br/>
1577 </p></li>
1578 <li><p>
1579 Если код завершения команды равен нулю,
1580 команда была выполнена без ошибок.
1581 Команды, код завершения которых отличен от нуля, выделяются цветом.
1582 <table>
1583 <tr class='command'>
1584 <td class='script'>
1585 <pre class='_wrong_cline'>
1586 \$ test 5 -lt 4</pre>
1587 </pre>
1588 </td>
1589 </tr>
1590 </table>
1591 Обратите внимание на то, что код завершения команды может быть отличен от нуля
1592 не только в тех случаях, когда команда была выполнена с ошибкой.
1593 Многие команды используют код завершения, например, для того чтобы показать результаты проверки
1594 <br/>
1595 </p></li>
1596 <li><p>
1597 Команды, ход выполнения которых был прерван пользователем, выделяются цветом.
1598 <table>
1599 <tr class='command'>
1600 <td class='script'>
1601 <pre class='_interrupted_cline'>
1602 \$ find / -name abc</pre>
1603 <pre class='interrupted_output'>find: /home/devi-orig/.gnome2: Keine Berechtigung
1604 find: /home/devi-orig/.gnome2_private: Keine Berechtigung
1605 find: /home/devi-orig/.nautilus/metafiles: Keine Berechtigung
1606 find: /home/devi-orig/.metacity: Keine Berechtigung
1607 find: /home/devi-orig/.inkscape: Keine Berechtigung
1608 ^C
1609 </pre>
1610 </td>
1611 </tr>
1612 </table>
1613 <br/>
1614 </p></li>
1615 <li><p>
1616 Команды, выполненные с привилегиями суперпользователя,
1617 выделяются слева красной чертой.
1618 <table>
1619 <tr class='command'>
1620 <td class='script'>
1621 <pre class='_root_cline'>
1622 # id</pre>
1623 <pre class='_root_output'>
1624 uid=0(root) gid=0(root) Gruppen=0(root)
1625 </pre>
1626 </td>
1627 </tr>
1628 </table>
1629 <br/>
1630 </p></li>
1631 <li><p>
1632 Изменения, внесённые в текстовый файл с помощью редактора,
1633 запоминаются и показываются в журнале в формате ed.
1634 Строки, начинающиеся символом "&lt;", удалены, а строки,
1635 начинающиеся символом "&gt;" -- добавлены.
1636 <table>
1637 <tr class='command'>
1638 <td class='script'>
1639 <pre class='cline'>
1640 \$ vi ~/.bashrc</pre>
1641 <table><tr><td width='5'/><td class='diff'><pre>2a3,5
1642 &gt; if [ -f /usr/local/etc/bash_completion ]; then
1643 &gt; . /usr/local/etc/bash_completion
1644 &gt; fi
1645 </pre></td></tr></table></td>
1646 </tr>
1647 </table>
1648 <br/>
1649 </p></li>
1650 <li><p>
1651 Для того чтобы изменить файл в соответствии с показанными в диффшоте
1652 изменениями, можно воспользоваться командой patch.
1653 Нужно скопировать изменения, запустить программу patch, указав в
1654 качестве её аргумента файл, к которому применяются изменения,
1655 и всавить скопированный текст:
1656 <table>
1657 <tr class='command'>
1658 <td class='script'>
1659 <pre class='cline'>
1660 \$ patch ~/.bashrc</pre>
1661 </td>
1662 </tr>
1663 </table>
1664 В данном случае изменения применяются к файлу ~/.bashrc
1665 </p></li>
1666 <li><p>
1667 Для того чтобы получить краткую справочную информацию о команде,
1668 нужно подвести к ней мышь. Во всплывающей подсказке появится краткое
1669 описание команды.
1670 </p>
1671 <p>
1672 Если справочная информация о команде есть,
1673 команда выделяется голубым фоном, например: <span class="with_hint" title="главный текстовый редактор Unix">vi</span>.
1674 Если справочная информация отсутствует,
1675 команда выделяется розовым фоном, например: <span class="without_hint">notepad.exe</span>.
1676 Справочная информация может отсутствовать в том случае,
1677 если (1) команда введена неверно; (2) если распознавание команды LiLaLo выполнено неверно;
1678 (3) если информация о команде неизвестна LiLaLo.
1679 Последнее возможно для редких команд.
1680 </p></li>
1681 <li><p>
1682 Большие, в особенности многострочные, всплывающие подсказки лучше
1683 всего показываются браузерами KDE Konqueror, Apple Safari и Microsoft Internet Explorer.
1684 В браузерах Mozilla и Firefox они отображаются не полностью,
1685 а вместо перевода строки выводится специальный символ.
1686 </p></li>
1687 <li><p>
1688 Время ввода команды, показанное в журнале, соответствует времени
1689 <i>начала ввода командной строки</i>, которое равно тому моменту,
1690 когда на терминале появилось приглашение интерпретатора
1691 </p></li>
1692 <li><p>
1693 Имя терминала, на котором была введена команда, показано в специальном блоке.
1694 Этот блок показывается только в том случае, если терминал
1695 текущей команды отличается от терминала предыдущей.
1696 </p></li>
1697 <li><p>
1698 Вывод не интересующих вас в настоящий момент элементов журнала,
1699 таких как время, имя терминала и других, можно отключить.
1700 Для этого нужно воспользоваться <a href='#visibility_form'>формой управления журналом</a>
1701 вверху страницы.
1702 </p></li>
1703 <li><p>
1704 Небольшие комментарии к командам можно вставлять прямо из командной строки.
1705 Комментарий вводится прямо в командную строку, после символов #^ или #v.
1706 Символы ^ и v показывают направление выбора команды, к которой относится комментарий:
1707 ^ - к предыдущей, v - к следующей.
1708 Например, если в командной строке было введено:
1709 <pre class='cline'>
1710 \$ whoami
1711 </pre>
1712 <pre class='output'>
1713 user
1714 </pre>
1715 <pre class='cline'>
1716 \$ #^ Интересно, кто я?
1717 </pre>
1718 в журнале это будет выглядеть так:
1720 <pre class='cline'>
1721 \$ whoami
1722 </pre>
1723 <pre class='output'>
1724 user
1725 </pre>
1726 <table class='note'><tr><td width='100%' class='note_text'>
1727 <tr> <td> Интересно, кто я?<br/> </td></tr></table>
1728 </p></li>
1729 <li><p>
1730 Если комментарий содержит несколько строк,
1731 его можно вставить в журнал следующим образом:
1732 <pre class='cline'>
1733 \$ whoami
1734 </pre>
1735 <pre class='output'>
1736 user
1737 </pre>
1738 <pre class='cline'>
1739 \$ cat > /dev/null #^ Интересно, кто я?
1740 </pre>
1741 <pre class='output'>
1742 Программа whoami выводит имя пользователя, под которым
1743 мы зарегистрировались в системе.
1745 Она не может ответить на вопрос о нашем назначении
1746 в этом мире.
1747 </pre>
1748 В журнале это будет выглядеть так:
1749 <table>
1750 <tr class='command'>
1751 <td class='script'>
1752 <pre class='cline'>
1753 \$ whoami</pre>
1754 <pre class='output'>user
1755 </pre>
1756 <table class='note'><tr><td class='note_title'>Интересно, кто я?</td></tr><tr><td width='100%' class='note_text'>
1757 Программа whoami выводит имя пользователя, под которым<br/>
1758 мы зарегистрировались в системе.<br/>
1759 <br/>
1760 Она не может ответить на вопрос о нашем назначении<br/>
1761 в этом мире.<br/>
1762 </td></tr></table>
1763 </td>
1764 </tr>
1765 </table>
1766 Для разделения нескольких абзацев между собой
1767 используйте символ "-", один в строке.
1768 <br/>
1769 </p></li>
1770 <li><p>
1771 Комментарии, не относящиеся непосредственно ни к какой из команд,
1772 добавляются точно таким же способом, только вместо симолов #^ или #v
1773 нужно использовать символы #=
1774 </p></li>
1776 <p><li>
1777 Содержимое файла может быть показано в журнале.
1778 Для этого его нужно вывести с помощью программы cat.
1779 Если вывод команды отметить симоволами #!,
1780 содержимое файла будет показано в журнале
1781 в специально отведённой для этого секции.
1782 </li></p>
1784 <p>
1785 <li>
1786 Для того чтобы вставить скриншот интересующего вас окна в журнал,
1787 нужно воспользоваться командой l3shot.
1788 После того как команда вызвана, нужно с помощью мыши выбрать окно, которое
1789 должно быть в журнале.
1790 </li>
1791 </p>
1793 <p>
1794 <li>
1795 Команды в журнале расположены в хронологическом порядке.
1796 Если две команды давались одна за другой, но на разных терминалах,
1797 в журнале они будут рядом, даже если они не имеют друг к другу никакого отношения.
1798 <pre>
1803 </pre>
1804 Группы команд, выполненных на разных терминалах, разделяются специальной линией.
1805 Под этой линией в правом углу показано имя терминала, на котором выполнялись команды.
1806 Для того чтобы посмотреть команды только одного сенса,
1807 нужно щёкнуть по этому названию.
1808 </li>
1809 </p>
1810 </ol>
1811 HELP
1813 $Html_About = <<ABOUT;
1814 <p>
1815 <a href='http://xgu.ru/lilalo/'>LiLaLo</a> (L3) расшифровывается как Live Lab Log.<br/>
1816 Программа разработана для повышения эффективности обучения Unix/Linux-системам.<br/>
1817 (c) Игорь Чубин, 2004-2006<br/>
1818 </p>
1819 ABOUT
1820 $Html_About.='$Id$ </p>';
1822 $Html_JavaScript = <<JS;
1823 function getElementsByClassName(Class_Name)
1825 var Result=new Array();
1826 var All_Elements=document.all || document.getElementsByTagName('*');
1827 for (i=0; i<All_Elements.length; i++)
1828 if (All_Elements[i].className==Class_Name)
1829 Result.push(All_Elements[i]);
1830 return Result;
1832 function ShowHide (name)
1834 elements=getElementsByClassName(name);
1835 for(i=0; i<elements.length; i++)
1836 if (elements[i].style.display == "none")
1837 elements[i].style.display = "";
1838 else
1839 elements[i].style.display = "none";
1840 //if (elements[i].style.visibility == "hidden")
1841 // elements[i].style.visibility = "visible";
1842 //else
1843 // elements[i].style.visibility = "hidden";
1845 function filter_by_output(text)
1848 var jjj=0;
1850 elements=getElementsByClassName('command');
1851 for(i=0; i<elements.length; i++) {
1852 subelems = elements[i].getElementsByTagName('pre');
1853 for(j=0; j<subelems.length; j++) {
1854 if (subelems[j].className = 'output') {
1855 var str = new String(subelems[j].nodeValue);
1856 if (jjj != 1) {
1857 alert(str);
1858 jjj=1;
1860 if (str.indexOf(text) >0)
1861 subelems[j].style.display = "none";
1862 else
1863 subelems[j].style.display = "";
1871 JS
1873 $SetCursorPosition_JS = <<JS;
1874 function setCursorPosition(oInput,oStart,oEnd) {
1875 oInput.focus();
1876 if( oInput.setSelectionRange ) {
1877 oInput.setSelectionRange(oStart,oEnd);
1878 } else if( oInput.createTextRange ) {
1879 var range = oInput.createTextRange();
1880 range.collapse(true);
1881 range.moveEnd('character',oEnd);
1882 range.moveStart('character',oStart);
1883 range.select();
1886 JS
1888 %Search_Machines = (
1889 "google" => { "query" => "http://www.google.com/search?q=" ,
1890 "icon" => "$Config{frontend_google_ico}" },
1891 "freebsd" => { "query" => "http://www.freebsd.org/cgi/man.cgi?query=",
1892 "icon" => "$Config{frontend_freebsd_ico}" },
1893 "linux" => { "query" => "http://man.he.net/?topic=",
1894 "icon" => "$Config{frontend_linux_ico}"},
1895 "opennet" => { "query" => "http://www.opennet.ru/search.shtml?words=",
1896 "icon" => "$Config{frontend_opennet_ico}"},
1897 "local" => { "query" => "http://www.freebsd.org/cgi/man.cgi?query=",
1898 "icon" => "$Config{frontend_local_ico}" },
1900 );
1902 %Elements_Visibility = (
1903 "0 new_commands_table" => "новые команды",
1904 "1 diff" => "редактор",
1905 "2 time" => "время",
1906 "3 ttychange" => "терминал",
1907 "4 wrong_output wrong_cline wrong_root_output wrong_root_cline"
1908 => "команды с ненулевым кодом завершения",
1909 "5 mistyped_output mistyped_cline mistyped_root_output mistyped_root_cline"
1910 => "неверно набранные команды",
1911 "6 interrupted_output interrupted_cline interrupted_root_output interrupted_root_cline"
1912 => "прерванные команды",
1913 "7 tab_completion_output tab_completion_cline"
1914 => "продолжение с помощью tab"
1915 );
1917 @Day_Name = qw/ Воскресенье Понедельник Вторник Среда Четверг Пятница Суббота /;
1918 @Month_Name = qw/ Январь Февраль Март Апрель Май Июнь Июль Август Сентябрь Октябрь Ноябрь Декабрь /;
1919 @Of_Month_Name = qw/ Января Февраля Марта Апреля Мая Июня Июля Августа Сентября Октября Ноября Декабря /;
1925 # Временно удалённый код
1926 # Возможно, он не понадобится уже никогда
1929 sub search_by
1931 my $sm = shift;
1932 my $topic = shift;
1933 $topic =~ s/ /+/;
1935 return "<a href='". $Search_Machines{$sm}->{"query"}."$topic'><img width='16' height='16' src='".
1936 $Search_Machines{$sm}->{"icon"}."' border='0'/></a>";
1942 ########################################################################################
1944 # mywi
1955 sub mywi_init
1957 our $MyWiFile = "/home/devi/mywi/mywi.txt";
1958 our $MyWiLog = "/home/devi/mywi/mywi.log";
1959 our $section="";
1961 our @MywiTXT; # Массив текстовых записей mywi
1962 our %MywiHASH; # Хэш массивов записей
1963 our %Query;
1965 load_mywitxt($MyWiFile, \@MywiTXT, \%MywiHASH);
1968 sub mywi_process_query($)
1970 # Сделать подсказку по заданному запросу
1971 # $_[0] - тема для подсказки
1973 # Возвращает:
1974 # строку-подсказку
1977 my $query = shift;
1978 parse_query($query, \%Query);
1979 $result = search_in_txt(\%Query, \@MywiTXT, \%MywiHASH);
1981 if (!$result) {
1982 #add_to_log(\%Query, $MyWiLog);
1983 return "$query nothing appropriate. Logged. ".join (";",%Query);
1986 return $result;
1989 ####################################################################################
1990 # private section
1991 ####################################################################################
1993 sub load_mywitxt
1995 # Загрузить файл с записями Mywi_TXT
1996 # в массив
1997 # $_[0] - указатель на массив для загрузки
1998 # $_[1] - имя файла для загрузки
2001 my $MyWiFile = $_[0];
2002 my $MywiTXT = $_[1];
2003 my $MywiHASH = $_[2];
2005 open (MW, "$MyWiFile") or die "Can't open $MyWiFile for reading";
2006 binmode MW, ":utf8";
2007 @{$MywiTXT} = <MW>;
2008 close (MWF);
2010 for my $mywi_line (@{$MywiTXT}) {
2011 my $topic = $mywi_line;
2012 $topic =~ s@\s*\(.*\n@@;
2013 push @{$$MywiHASH{"$topic"}}, $mywi_line;
2014 # $MywiHASH{"$topic"} .= $mywi_line;
2018 sub parse_query
2020 # Строка запроса:
2021 # [format:]topic[(section)]
2022 # Элементы format и topic являются не обязательными
2024 # $_[0] - строка запроса
2025 # $_[1] - ссылка на хэш запроса
2028 my $query_string = shift;
2029 my $query_hash = shift;
2031 %{$query_hash} = (
2032 "format" => "txt",
2033 "section" => "",
2034 "topic" => "",
2035 );
2037 if ($query_string =~ s/^([^:]*)://) {
2038 $query_hash->{"format"} = $1 || "txt";
2040 if ($query_string =~ s/\(([^(]*)\)$//) {
2041 $query_hash->{"section"} = $1 || "";
2043 $query_hash->{"topic"} = $query_string;
2047 sub search_in_txt
2049 # Выполнить поиск в текстовой базе
2050 # по известному запросу
2051 # $_[0] -- ссылка на хэш запроса
2052 # $_[1] -- ссылка на массив текстовых записей
2053 # $_[2] -- ссылка на хэш массивов текстовых записей
2054 # Результат:
2055 # найденная текстовая запись в заданном формате
2058 my %Query = %{$_[0]};
2059 my %MywiHASH = %{$_[2]};
2061 my $topic = $Query{"topic"};
2062 my $section = $Query{"section"};
2063 my $result = "";
2065 return join("\n",@{$MywiHASH{"$topic"}})."\n";
2067 for my $l (@{$$_[2]{$topic}}) {
2068 # for my $l (@{$_[1]}) {
2069 my $line = $l;
2070 if (
2071 ($section and $line =~ /^\s*\Q$topic\E\s*\($section*\)\s*-/ )
2072 or (not $section and $line =~ /^\s*\Q$topic\E\s*(\([^)]*\)?)\s*-/) ) {
2073 $line =~ s/^.* -//mg if ($Config{"short"});
2074 $result .= "<para>$line</para>";
2077 return $result;
2081 sub add_to_log($$)
2083 # Если в базе отсутствует информация по данной теме,
2084 # сделать предположение доступным способом
2085 # и добавить его в базу
2086 # или просто сделать отметку о необходимости
2087 # расширения базы
2089 # Добавить запись в журнал
2090 # $_[0] - запись (ссылка на хэш)
2091 # $_[1] - имя файла-журнала
2094 my $query = $_[0];
2095 my $MyWiLog = $_[1];
2097 open (MWF, ">>:utf8", $MyWiLog) or die "Can't open $MyWiLog for writing";
2098 my $my_guess = mywi_guess($query);
2099 print MWF "$my_guess\n";
2100 close(MWF);
2103 sub mywi_guess($)
2104 # Сформировать исходную строку для журнала по заданному запросу
2105 # Если секция принадлежит 0..9, в качестве основы для результирующего текста использовать whatis
2106 # $_[0] - запись (ссылка на хэш)
2108 # Возвращает:
2109 # строку-предположение
2111 my %query = %{$_[0]};
2113 my $topic = $query{"topic"};
2114 my $section = $query{"section"};
2116 my $result = "$topic($section)";
2117 if (!$section or $section =~ /^[1-9]$/)
2119 # Запрос из категории 1-9
2120 # Об этом может знать whatis
2121 $result = `LANG=C whatis -- "$topic"`;
2122 if ($result =~ /nothing appropriate/i) {
2123 $result = $topic;
2124 $result .= "($section)" if $section;
2126 else {
2127 1 while ($result =~ s/(\s+)-(\s+)/$1+$2/sg);
2128 $result =~ s/\s+\(/(/;
2129 chomp $result;
2132 return $result;