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