--- loncom/xml/lonxml.pm	2003/03/25 22:51:48	1.241
+++ loncom/xml/lonxml.pm	2003/08/21 15:51:41	1.273
@@ -1,7 +1,7 @@
 # The LearningOnline Network with CAPA
 # XML Parser Module 
 #
-# $Id: lonxml.pm,v 1.241 2003/03/25 22:51:48 albertel Exp $
+# $Id: lonxml.pm,v 1.273 2003/08/21 15:51:41 sakharuk Exp $
 #
 # Copyright Michigan State University Board of Trustees
 #
@@ -69,6 +69,8 @@ use Safe::Hole();
 use Math::Cephes();
 use Math::Random();
 use Opcode();
+use POSIX qw(strftime);
+
 
 sub register {
   my ($space,@taglist) = @_;
@@ -95,6 +97,8 @@ use Apache::run();
 use Apache::londefdef();
 use Apache::scripttag();
 use Apache::edit();
+use Apache::inputtags();
+use Apache::outputtags();
 use Apache::lonnet();
 use Apache::File();
 use Apache::loncommon();
@@ -151,6 +155,10 @@ $Apache::lonxml::counter_changed=0;
 #internal check on whether to look at style defs
 $Apache::lonxml::usestyle=1;
 
+#locations used to store the parameter string for style substitutions
+$Apache::lonxml::style_values='';
+$Apache::lonxml::style_end_values='';
+
 sub xmlbegin {
   my $output='';
   if ($ENV{'browser.mathml'}) {
@@ -196,6 +204,13 @@ sub xmlend {
                  my $message=$contrib{$idx.':message'};
                  $message=~s/\n/\<br \/\>/g;
 		 $message=&Apache::lontexconvert::msgtexconverted($message);
+                 if ($contrib{$idx.':attachmenturl'}) {
+                     my ($fname,$ft)
+                        =($contrib{$idx.':attachmenturl'}=~/\/(\w+)\.(\w+)$/);
+		     $message.='<p>Attachment: <a href="'.
+	       &Apache::lonnet::tokenwrapper($contrib{$idx.':attachmenturl'}).
+                     '"><tt>'.$fname.'.'.$ft.'</tt></a>';
+                 }
                  if ($message) {
                   if ($hidden) {
 		      $message='<font color="#888888">'.$message.'</font>';
@@ -248,7 +263,7 @@ sub xmlend {
           }
           if ($discussiononly) {
 	      $discussion.=(<<ENDDISCUSS);
-<form action="/adm/feedback" method="post" name="mailform">
+<form action="/adm/feedback" method="post" name="mailform" enctype="multipart/form-data">
 <input type="submit" name="discuss" value="Post Discussion" />
 <input type="submit" name="anondiscuss" value="Post Anonymous Discussion" />
 <input type="hidden" name="symb" value="$symb" />
@@ -257,6 +272,9 @@ sub xmlend {
 <font size="1">Note: in anonymous discussion, your name is visible only to
 course faculty</font><br />
 <textarea name=comment cols=60 rows=10 wrap=hard></textarea>
+<p>
+Attachment (128 KB max size): <input type="file" name="attachment" />
+</p>
 </form>
 ENDDISCUSS
              $discussion.=&Apache::lonfeedback::generate_preview_button();
@@ -370,8 +388,11 @@ sub printtokenheader {
 sub fontsettings() {
     my $headerstring='';
     if (($ENV{'browser.os'} eq 'mac') && (!$ENV{'browser.mathml'})) { 
-         $headerstring.=
-             '<meta Content-Type="text/html; charset=x-mac-roman">';
+	$headerstring.=
+	    '<meta Content-Type="text/html; charset=x-mac-roman">';
+    } elsif (!$ENV{'browser.mathml'} && $ENV{'browser.unicode'}) {
+	$headerstring.=
+	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
     }
     return $headerstring;
 }
@@ -391,6 +412,7 @@ sub xmlparse {
  &Apache::inputtags::initialize_inputtags();
  &Apache::outputtags::initialize_outputtags();
  &Apache::edit::initialize_edit();
+
 #
 # do we have a course style file?
 #
@@ -407,8 +429,7 @@ sub xmlparse {
        }
     }
  }
-
- #&printalltags();
+#&printalltags();
  my @pars = ();
  my $pwd=$ENV{'request.filename'};
  $pwd =~ s:/[^/]*$::;
@@ -427,6 +448,7 @@ sub xmlparse {
 
  my $finaloutput = &inner_xmlparse($target,\@stack,\@parstack,\@pars,
 				   $safeeval,\%style_for_target);
+
  if ($ENV{'request.uri'}) {
     &writeallows($ENV{'request.uri'});
  }
@@ -456,23 +478,25 @@ sub htmlclean {
 }
 
 sub latex_special_symbols {
-    my ($current_token,$stack,$parstack,$where)=@_;
+    my ($string,$where)=@_;
     if ($where eq 'header') {
-	$current_token =~ s/(\\|_|\^)/ /g;
-	$current_token =~ s/(\$|%|\#|&|\{|\})/\\$1/g;
+	$string =~ s/(\\|_|\^)/ /g;
+	$string =~ s/(\$|%|\#|&|\{|\})/\\$1/g;
+	$string =~ s/_/ /g;
     } else {
-	$current_token=~s/\\ /\\char92 /g;
-	$current_token=~s/\^/\\char94 /g;
-	$current_token=~s/\~/\\char126 /g;
-	$current_token=~s/(&[^a-z\#])/\\$1/g;
-	$current_token=~s/([^&])\#/$1\\#/g;
-	$current_token=~s/(\$|_|{|})/\\$1/g;
-	$current_token=~s/\\char92 /\\texttt{\\char92}/g;
-	$current_token=~s/(>|<)/\$$1\$/g; #more or less
-	if ($current_token=~m/\d%/) {$current_token =~ s/(\d)%/$1\\%/g;} #percent after digit
-	if ($current_token=~m/\s%/) {$current_token =~ s/(\s)%/$1\\%/g;} #persent after space
+	$string=~s/\\ /\\char92 /g;
+	$string=~s/\^/\\char94 /g;
+	$string=~s/\~/\\char126 /g;
+	$string=~s/(&[^A-Za-z\#])/\\$1/g;
+	$string=~s/([^&])\#/$1\\#/g;
+	$string=~s/(\$|_|{|})/\\$1/g;
+	$string=~s/\\char92 /\\texttt{\\char92}/g;
+	$string=~s/(>|<)/\$$1\$/g; #more or less
+	if ($string=~m/\d%/) {$string =~ s/(\d)%/$1\\%/g;} #percent after digit
+	if ($string=~m/\s%/) {$string =~ s/(\s)%/$1\\%/g;} #percent after space
+	if ($string eq '%.') {$string = '\%.';} #percent at the end of statement
     }
-    return $current_token;
+    return $string;
 }
 
 sub inner_xmlparse {
@@ -480,9 +504,10 @@ sub inner_xmlparse {
   my $finaloutput = '';
   my $result;
   my $token;
+  my $dontpop=0;
   while ( $#$pars > -1 ) {
     while ($token = $$pars['-1']->get_token) {
-      if (($token->[0] eq 'T') || ($token->[0] eq 'C') || ($token->[0] eq 'D') ) {
+      if (($token->[0] eq 'T') || ($token->[0] eq 'C') ) {
 	if ($metamode<1) {
 	    my $text=$token->[1];
 	    if ($token->[0] eq 'C' && $target eq 'tex') {
@@ -491,8 +516,13 @@ sub inner_xmlparse {
 	    }
 	    $result.=$text;
 	}
+      } elsif (($token->[0] eq 'D')) {
+	if ($metamode<1 && $target eq 'web') {
+	    my $text=$token->[1];
+	    $result.=$text;
+	}
       } elsif ($token->[0] eq 'PI') {
-	if ($metamode<1) {
+	if ($metamode<1 && $target eq 'web') {
 	  $result=$token->[2];
 	}
       } elsif ($token->[0] eq 'S') {
@@ -507,48 +537,57 @@ sub inner_xmlparse {
 	    my $string=$$style_for_target{$token->[1]}.
 	      '<LONCAPA_INTERNAL_TURN_STYLE_ON />';
 	    &Apache::lonxml::newparser($pars,\$string);
+	    $Apache::lonxml::style_values=$$parstack[-1];
+	    $Apache::lonxml::style_end_values=$$parstack[-1];
 	} else {
 	  $result = &callsub("start_$token->[1]", $target, $token, $stack,
 			     $parstack, $pars, $safeeval, $style_for_target);
 	}
       } elsif ($token->[0] eq 'E') {
-	#clear out any tags that didn't end
-	while ($token->[1] ne $$stack['-1'] && ($#$stack > -1)) {
-	  my $lasttag=$$stack[-1];
-	  if ($token->[1] =~ /^$lasttag$/i) {
-	    &Apache::lonxml::warning('Using tag &lt;/'.$token->[1].'&gt; as end tag to &lt;'.$$stack[-1].'&gt;');
-	    last;
-	  } else {
-	    &Apache::lonxml::warning('Found tag &lt;/'.$token->[1].'&gt; when looking for &lt;/'.$$stack[-1].'&gt; in file');
-	    &end_tag($stack,$parstack,$token);
-	  }
-	}
-
 	if ($Apache::lonxml::usestyle &&
 	    exists($$style_for_target{'/'."$token->[1]"})) {
 	    $Apache::lonxml::usestyle=0;
 	    my $string=$$style_for_target{'/'.$token->[1]}.
-	      '<LONCAPA_INTERNAL_TURN_STYLE_ON />';
+	      '<LONCAPA_INTERNAL_TURN_STYLE_ON end="'.$token->[1].'" />';
 	    &Apache::lonxml::newparser($pars,\$string);
+	    $Apache::lonxml::style_values=$Apache::lonxml::style_end_values;
+	    $Apache::lonxml::style_end_values='';
+	    $dontpop=1;
 	} else {
-	  $result = &callsub("end_$token->[1]", $target, $token, $stack,
-			     $parstack, $pars,$safeeval, $style_for_target);
+	    #clear out any tags that didn't end
+	    while ($token->[1] ne $$stack['-1'] && ($#$stack > -1)) {
+		my $lasttag=$$stack[-1];
+		if ($token->[1] =~ /^$lasttag$/i) {
+		    &Apache::lonxml::warning('Using tag &lt;/'.$token->[1].'&gt; on line '.$token->[3].' as end tag to &lt;'.$$stack[-1].'&gt;');
+		    last;
+		} else {
+		    &Apache::lonxml::warning('Found tag &lt;/'.$token->[1].'&gt; on line '.$token->[3].' when looking for &lt;/'.$$stack[-1].'&gt; in file');
+		    &end_tag($stack,$parstack,$token);
+		}
+	    }
+	    $result = &callsub("end_$token->[1]", $target, $token, $stack,
+			       $parstack, $pars,$safeeval, $style_for_target);
 	}
       } else {
 	&Apache::lonxml::error("Unknown token event :$token->[0]:$token->[1]:");
       }
       #evaluate variable refs in result
       if ($result ne "") {
+	  my $extras;
+	  if (!$Apache::lonxml::usestyle) {
+	      $extras=$Apache::lonxml::style_values;
+	  }
 	if ( $#$parstack > -1 ) {
-	  $result=&Apache::run::evaluate($result,$safeeval,$$parstack[-1]);
+	  $result=&Apache::run::evaluate($result,$safeeval,$extras.$$parstack[-1]);
 	} else {
-	  $result= &Apache::run::evaluate($result,$safeeval,'');
+	  $result= &Apache::run::evaluate($result,$safeeval,$extras);
 	}
       }
       if (($token->[0] eq 'T') || ($token->[0] eq 'C') || ($token->[0] eq 'D') ) {
-	if ($target eq 'tex') {
-	    $result=&latex_special_symbols($result,$stack,$parstack);
-	}
+	  #Style file definitions should be correct
+	  if ($target eq 'tex' && ($Apache::lonxml::usestyle)) {
+	      $result=&latex_special_symbols($result);
+	  }
       }
 
       # Encode any high ASCII characters
@@ -562,9 +601,10 @@ sub inner_xmlparse {
       }
       $result = '';
 
-      if ($token->[0] eq 'E') { 
+      if ($token->[0] eq 'E' && !$dontpop) {
 	&end_tag($stack,$parstack,$token);
       }
+      $dontpop=0;
     }	
     if ($#$pars > -1) {
 	pop @$pars;
@@ -707,6 +747,7 @@ sub init_safespace {
   $safeeval->permit("sort");
   $safeeval->deny(":base_io");
   $safehole->wrap(\&Apache::scripttag::xmlparse,$safeeval,'&xmlparse');
+  $safehole->wrap(\&Apache::outputtags::multipart,$safeeval,'&multipart');
   $safehole->wrap(\&Apache::lonnet::EXT,$safeeval,'&EXT');
   
   $safehole->wrap(\&Math::Cephes::asin,$safeeval,'&asin');
@@ -788,6 +829,7 @@ sub init_safespace {
   my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
   $rndseed=&Apache::lonnet::rndseed($symb,$courseid,$domain,$name);
   $safeinit .= ';$external::randomseed='.$rndseed.';';
+  &Apache::lonxml::debug("Setting rndseed to $rndseed");
   &Apache::run::run($safeinit,$safeeval);
 }
 
@@ -887,18 +929,23 @@ sub get_all_text_unbalanced {
 }
 
 sub increment_counter {
-    $Apache::lonxml::counter++;
+    my ($increment) = @_;
+    if (defined($increment) && $increment gt 0) {
+	$Apache::lonxml::counter+=$increment;
+    } else {
+	$Apache::lonxml::counter++;
+    }
     $Apache::lonxml::counter_changed=1;
 }
 
 sub init_counter {
     if (defined($ENV{'form.counter'})) {
 	$Apache::lonxml::counter=$ENV{'form.counter'};
+	$Apache::lonxml::counter_changed=0;
     } else {
 	$Apache::lonxml::counter=1;
-	&store_counter();
+	$Apache::lonxml::counter_changed=1;
     }
-    $Apache::lonxml::counter_changed=0;
 }
 
 sub store_counter {
@@ -907,83 +954,105 @@ sub store_counter {
 }
 
 sub get_all_text {
- my($tag,$pars)= @_;
- &Apache::lonxml::debug("Got a ".ref($pars));
- my $gotfullstack=1;
- if (ref($pars) ne 'ARRAY') {
-     $gotfullstack=0;
-     $pars=[$pars];
- }
- my $depth=0;
- my $token;
- my $result='';
- if ( $tag =~ m:^/: ) { 
-   my $tag=substr($tag,1); 
-   #&Apache::lonxml::debug("have:$tag:");
-   my $top_empty=0;
-   while (($depth >=0) && ($#$pars > -1) && (!$top_empty)) {
-     while (($depth >=0) && ($token = $$pars[-1]->get_token)) {
-       #&Apache::lonxml::debug("e token:$token->[0]:$depth:$token->[1]:".$#$pars.":".$#Apache::lonxml::pwd);
-       if (($token->[0] eq 'T')||($token->[0] eq 'C')||($token->[0] eq 'D')) {
-	 $result.=$token->[1];
-       } elsif ($token->[0] eq 'PI') {
-	 $result.=$token->[2];
-       } elsif ($token->[0] eq 'S') {
-	 if ($token->[1] =~ /^$tag$/i) { $depth++; }
-	 $result.=$token->[4];
-       } elsif ($token->[0] eq 'E')  {
-	 if ( $token->[1] =~ /^$tag$/i) { $depth--; }
-	 #skip sending back the last end tag
-	 if ($depth > -1) { $result.=$token->[2]; } else {
-	   $$pars[-1]->unget_token($token);
-	 }
-       }
-     }
-     if (($depth >=0) && ($#$pars == 0) ) { $top_empty=1; }
-     if (($depth >=0) && ($#$pars > 0) ) {
-       pop(@$pars);
-       pop(@Apache::lonxml::pwd);
-     }
-   }
-   if ($top_empty && $depth >= 0) {
-       #never found the end tag ran out of text, throw error send back blank
-       &error('Never found end tag for &lt;'.$tag.'&gt;');
-       if ($gotfullstack) {
-	   my $newstring='</'.$tag.'>'.$result;
-	   &Apache::lonxml::newparser($pars,\$newstring);
-       }
-       $result='';
-   }
- } else {
-     while ($#$pars > -1) {
-	 while ($token = $$pars[-1]->get_token) {
-	     #&Apache::lonxml::debug("s token:$token->[0]:$depth:$token->[1]");
-	     if (($token->[0] eq 'T')||($token->[0] eq 'C')||
-		 ($token->[0] eq 'D')) {
-		 $result.=$token->[1];
-	     } elsif ($token->[0] eq 'PI') {
-		 $result.=$token->[2];
-	     } elsif ($token->[0] eq 'S') {
-		 if ( $token->[1] =~ /^$tag$/i) {
-		     $$pars[-1]->unget_token($token); last;
-		 } else {
-		     $result.=$token->[4];
-		 }
-	     } elsif ($token->[0] eq 'E')  {
-		 $result.=$token->[2];
-	     }
-	 }
-	 if (($#$pars > 0) ) {
-	     pop(@$pars);
-	     pop(@Apache::lonxml::pwd);
-	 } else { last; }
-     }
- }
- if ($result =~ m|<LONCAPA_INTERNAL_TURN_STYLE_ON />|) {
-     $Apache::lonxml::usestyle=1;
- }
- #&Apache::lonxml::debug("Exit:$result:");
- return $result
+    my($tag,$pars,$style)= @_;
+    &Apache::lonxml::debug("Got a ".ref($pars));
+    my $gotfullstack=1;
+    if (ref($pars) ne 'ARRAY') {
+	$gotfullstack=0;
+	$pars=[$pars];
+    }
+    &Apache::lonxml::debug("Got a ".ref($style));
+    if (ref($style) ne 'HASH') {
+	$style={};
+    } else {
+	&Apache::lonhomework::showhash(%$style);
+    }
+    my $depth=0;
+    my $token;
+    my $result='';
+    if ( $tag =~ m:^/: ) { 
+	my $tag=substr($tag,1); 
+	#&Apache::lonxml::debug("have:$tag:");
+	my $top_empty=0;
+	while (($depth >=0) && ($#$pars > -1) && (!$top_empty)) {
+	    while (($depth >=0) && ($token = $$pars[-1]->get_token)) {
+		#&Apache::lonxml::debug("e token:$token->[0]:$depth:$token->[1]:".$#$pars.":".$#Apache::lonxml::pwd);
+		if (($token->[0] eq 'T')||($token->[0] eq 'C')||($token->[0] eq 'D')) {
+		    $result.=$token->[1];
+		} elsif ($token->[0] eq 'PI') {
+		    $result.=$token->[2];
+		} elsif ($token->[0] eq 'S') {
+		    if ($token->[1] =~ /^$tag$/i) { $depth++; }
+		    if ($token->[1] =~ /^LONCAPA_INTERNAL_TURN_STYLE_ON$/i) { $Apache::lonxml::usestyle=1; }
+		    if ($token->[1] =~ /^LONCAPA_INTERNAL_TURN_STYLE_OFF$/i) { $Apache::lonxml::usestyle=0; }
+		    $result.=$token->[4];
+		} elsif ($token->[0] eq 'E')  {
+		    if ( $token->[1] =~ /^$tag$/i) { $depth--; }
+		    #skip sending back the last end tag
+		    if ($depth == 0 && exists($$style{'/'.$token->[1]})) {
+			my $string=
+			    '<LONCAPA_INTERNAL_TURN_STYLE_OFF end="yes" />'.
+				$$style{'/'.$token->[1]}.
+				    $token->[2].
+					'<LONCAPA_INTERNAL_TURN_STYLE_ON />';
+			&Apache::lonxml::newparser($pars,\$string);
+			#&Apache::lonxml::debug("reParsing $string");
+			next;
+		    }
+		    if ($depth > -1) {
+			$result.=$token->[2];
+		    } else {
+			$$pars[-1]->unget_token($token);
+		    }
+		}
+	    }
+	    if (($depth >=0) && ($#$pars == 0) ) { $top_empty=1; }
+	    if (($depth >=0) && ($#$pars > 0) ) {
+		pop(@$pars);
+		pop(@Apache::lonxml::pwd);
+	    }
+	}
+	if ($top_empty && $depth >= 0) {
+	    #never found the end tag ran out of text, throw error send back blank
+	    &error('Never found end tag for &lt;'.$tag.
+		   '&gt; current string <pre>'.
+		   &HTML::Entities::encode($result).
+		   '</pre>');
+	    if ($gotfullstack) {
+		my $newstring='</'.$tag.'>'.$result;
+		&Apache::lonxml::newparser($pars,\$newstring);
+	    }
+	    $result='';
+	}
+    } else {
+	while ($#$pars > -1) {
+	    while ($token = $$pars[-1]->get_token) {
+		#&Apache::lonxml::debug("s token:$token->[0]:$depth:$token->[1]");
+		if (($token->[0] eq 'T')||($token->[0] eq 'C')||
+		    ($token->[0] eq 'D')) {
+		    $result.=$token->[1];
+		} elsif ($token->[0] eq 'PI') {
+		    $result.=$token->[2];
+		} elsif ($token->[0] eq 'S') {
+		    if ( $token->[1] =~ /^$tag$/i) {
+			$$pars[-1]->unget_token($token); last;
+		    } else {
+			$result.=$token->[4];
+		    }
+		    if ($token->[1] =~ /^LONCAPA_INTERNAL_TURN_STYLE_ON$/i) { $Apache::lonxml::usestyle=1; }
+		    if ($token->[1] =~ /^LONCAPA_INTERNAL_TURN_STYLE_OFF$/i) { $Apache::lonxml::usestyle=0; }
+		} elsif ($token->[0] eq 'E')  {
+		    $result.=$token->[2];
+		}
+	    }
+	    if (($#$pars > 0) ) {
+		pop(@$pars);
+		pop(@Apache::lonxml::pwd);
+	    } else { last; }
+	}
+    }
+    #&Apache::lonxml::debug("Exit:$result:");
+    return $result
 }
 
 sub newparser {
@@ -995,8 +1064,6 @@ sub newparser {
   } else {
     push (@Apache::lonxml::pwd, $dir);
   } 
-#  &Apache::lonxml::debug("pwd:$#Apache::lonxml::pwd");
-#  &Apache::lonxml::debug("pwd:$Apache::lonxml::pwd[$#Apache::lonxml::pwd]");
 }
 
 sub parstring {
@@ -1007,7 +1074,7 @@ sub parstring {
       my $val=$token->[2]->{$_};
       $val =~ s/([\%\@\\\"\'])/\\$1/g;
       #if ($val =~ m/^[\%\@]/) { $val="\\".$val; }
-      $temp .= "my \$$_=\"$val\";"
+      $temp .= "my \$$_=\"$val\";";
     }
   }
   return $temp;
@@ -1072,8 +1139,10 @@ sub storefile {
     if (my $fh=Apache::File->new('>'.$file)) {
 	print $fh $contents;
         $fh->close();
+        return 1;
     } else {
-      &warning("Unable to save file $file");
+	&warning("Unable to save file $file");
+	return 0;
     }
 }
 
@@ -1100,13 +1169,8 @@ sub inserteditinfo {
       my ($result,$filecontents)=@_;
       $filecontents = &HTML::Entities::encode($filecontents);
 #      my $editheader='<a href="#editsection">Edit below</a><hr />';
-      my $xml_help = '<table><tr><td>'.
-	  &Apache::loncommon::help_open_topic("Greek_Symbols",'Greek Symbols',
-					      undef,undef,600)
-	      .'</td><td>'.
-          &Apache::loncommon::help_open_topic("Other_Symbols",'Other Symbols',
-					      undef,undef,600)
-	      .'</td></tr></table>';
+      my $xml_help = Apache::loncommon::helpLatexCheatsheet();
+      my $titledisplay=&display_title();
       my $buttons=(<<BUTTONS);
 <input type="submit" name="attemptclean" 
        value="Save and then attempt to clean HTML" />
@@ -1124,6 +1188,7 @@ $buttons<br />
 <br />$buttons
 <br />
 </form>
+$titledisplay
 ENDFOOTER
 #      $result=~s/(\<body[^\>]*\>)/$1$editheader/is;
       $result=~s/(\<\/body\>)/$editfooter/is;
@@ -1158,37 +1223,39 @@ sub get_target {
 }
 
 sub handler {
-  my $request=shift;
-
-  my $target=&get_target();
-
-  $Apache::lonxml::debug=0;
-
-  if ($ENV{'browser.mathml'}) {
-    $request->content_type('text/xml');
-  } else {
-    $request->content_type('text/html');
-  }
-  &Apache::loncommon::no_cache($request);
-  $request->send_http_header;
-
-  return OK if $request->header_only;
+    my $request=shift;
+    
+    my $target=&get_target();
+    
+    $Apache::lonxml::debug=$ENV{'user.debug'};
+    
+    if ($ENV{'browser.mathml'}) {
+	$request->content_type('text/xml');
+    } else {
+	$request->content_type('text/html');
+    }
+    &Apache::loncommon::no_cache($request);
+    $request->send_http_header;
+    
+    return OK if $request->header_only;
 
 
-  my $file=&Apache::lonnet::filelocation("",$request->uri);
+    my $file=&Apache::lonnet::filelocation("",$request->uri);
 #
 # Edit action? Save file.
 #
-  unless ($ENV{'request.state'} eq 'published') {
-      if (($ENV{'form.savethisfile'}) || ($ENV{'form.attemptclean'})) {
-	  &storefile($file,$ENV{'form.filecont'});
-      }
-  }
-  my %mystyle;
-  my $result = '';
-  my $filecontents=&Apache::lonnet::getfile($file);
-  if ($filecontents eq -1) {
-    $result=(<<ENDNOTFOUND);
+    unless ($ENV{'request.state'} eq 'published') {
+	if (($ENV{'form.savethisfile'}) || ($ENV{'form.attemptclean'})) {
+	    if (&storefile($file,$ENV{'form.filecont'})) {
+		$request->print("<font COLOR=\"#0000FF\">Updated: ". strftime("%d %b %H:%M:%S",localtime())." </font>");
+	    } 
+	}
+    }
+    my %mystyle;
+    my $result = '';
+    my $filecontents=&Apache::lonnet::getfile($file);
+    if ($filecontents eq -1) {
+	$result=(<<ENDNOTFOUND);
 <html>
 <head>
 <title>File not found</title>
@@ -1199,40 +1266,58 @@ sub handler {
 </html>
 ENDNOTFOUND
     $filecontents='';
-    if ($ENV{'request.state'} ne 'published') {
-      $filecontents=&createnewhtml();
-      $ENV{'form.editmode'}='Edit'; #force edit mode
-    }
-  } else {
-    unless ($ENV{'request.state'} eq 'published') {
-      if ($ENV{'form.attemptclean'}) {
-	$filecontents=&htmlclean($filecontents,1);
-      }
-    }
-    if (!$ENV{'form.editmode'} || $ENV{'form.viewmode'}) {
-      $result = &Apache::lonxml::xmlparse($request,$target,$filecontents,
-					  '',%mystyle);
+	if ($ENV{'request.state'} ne 'published') {
+	    $filecontents=&createnewhtml();
+	    $ENV{'form.editmode'}='Edit'; #force edit mode
+	}
+    } else {
+	unless ($ENV{'request.state'} eq 'published') {
+	    if ($ENV{'form.attemptclean'}) {
+		$filecontents=&htmlclean($filecontents,1);
+	    }
+#
+# we are in construction space, see if edit mode forced
+            &Apache::loncommon::get_unprocessed_cgi
+                          ($ENV{'QUERY_STRING'},['editmode']);
+	}
+	if (!$ENV{'form.editmode'} || $ENV{'form.viewmode'}) {
+	    $result = &Apache::lonxml::xmlparse($request,$target,$filecontents,
+						'',%mystyle);
+	}
     }
-  }
-
+    
 #
 # Edit action? Insert editing commands
 #
-  unless ($ENV{'request.state'} eq 'published') {
-    if ($ENV{'form.editmode'} && (!($ENV{'form.viewmode'}))) {
-	my $displayfile=$request->uri;
-        $displayfile=~s/^\/[^\/]*//;
-      $result='<html><body bgcolor="#FFFFFF"><h3>'.$displayfile.
-              '</h3></body></html>';
-      $result=&inserteditinfo($result,$filecontents);
+    unless ($ENV{'request.state'} eq 'published') {
+	if ($ENV{'form.editmode'} && (!($ENV{'form.viewmode'}))) {
+	    my $displayfile=$request->uri;
+	    $displayfile=~s/^\/[^\/]*//;
+	    $result='<html><body bgcolor="#FFFFFF"><h3>'.$displayfile.
+		'</h3></body></html>';
+	    $result=&inserteditinfo($result,$filecontents);
+	}
     }
-  }
-
-  writeallows($request->uri);
-
-  $request->print($result);
-
-  return OK;
+    
+    writeallows($request->uri);
+    
+
+    $request->print($result);
+    
+    return OK;
+}
+
+sub display_title {
+    my $result;
+    if ($ENV{'request.state'} eq 'construct') {
+	my $title=&Apache::lonnet::gettitle();
+	if (!defined($title) || $title eq '') {
+	    $title = $ENV{'request.filename'};
+	    $title = substr($title, rindex($title, '/') + 1);
+	}
+	$result = "<script type='text/javascript'>top.document.title = '$title - LON-CAPA Construction Space';</script>";
+    }
+    return $result;
 }
 
 sub debug {
@@ -1270,8 +1355,11 @@ sub error {
 
 sub warning {
   $warningcount++;
-  if ($ENV{'request.state'} eq 'construct') {
-    print "<b>W</b>ARNING<b>:</b>".join('<br />',@_)."<br />\n";
+  
+  if ($ENV{'form.grade_target'} ne 'tex') {
+      if ($ENV{'request.state'} eq 'construct' || $Apache::lonxml::debug) {
+        print "<b>W</b>ARNING<b>:</b>".join('<br />',@_)."<br />\n";
+      }
   }
 }
 
@@ -1333,7 +1421,7 @@ sub register_insert {
     my $line = $data[$i];
     if ( $line =~ /^\#/ || $line =~ /^\s*\n/) { next; }
     if ( $line =~ /TABLE/ ) { last; }
-    my ($tag,$descrip,$color,$function,$show) = split(/,/, $line);
+    my ($tag,$descrip,$color,$function,$show,$helpfile,$helpdesc) = split(/,/, $line);
     if ($tag) {
       $insertlist{"$tagnum.tag"} = $tag;
       $insertlist{"$tagnum.description"} = $descrip;
@@ -1341,6 +1429,8 @@ sub register_insert {
       $insertlist{"$tagnum.function"} = $function;
       if (!defined($show)) { $show='yes'; }
       $insertlist{"$tagnum.show"}= $show;
+      $insertlist{"$tagnum.helpfile"} = $helpfile;
+      $insertlist{"$tagnum.helpdesc"} = $helpdesc;
       $insertlist{"$tag.num"}=$tagnum;
       $tagnum++;
     }
@@ -1375,15 +1465,30 @@ sub description {
   return $insertlist{$tagnum.'.description'};
 }
 
+# Returns a list containing the help file, and the description
+sub helpinfo {
+  my ($token)=@_;
+  my $tagnum;
+  my $tag=$token->[1];
+  foreach my $namespace (reverse @Apache::lonxml::namespace) {
+    my $testtag=$namespace.'::'.$tag;
+    $tagnum=$insertlist{"$testtag.num"};
+    if (defined($tagnum)) { last; }
+  }
+  if (!defined ($tagnum)) { $tagnum=$Apache::lonxml::insertlist{"$tag.num"}; }
+  return ($insertlist{$tagnum.'.helpfile'}, $insertlist{$tagnum.'.helpdesc'});
+}
+
 # ----------------------------------------------------------------- whichuser
 # returns a list of $symb, $courseid, $domain, $name that is correct for
 # calls to lonnet functions for this setup.
 # - looks for form.grade_ parameters
 sub whichuser {
-  my ($symb,$courseid,$domain,$name);
+  my ($passedsymb)=@_;
+  my ($symb,$courseid,$domain,$name,$publicuser);
   if (defined($ENV{'form.grade_symb'})) {
     my $tmp_courseid=$ENV{'form.grade_courseid'};
-    my $allowed=&Apache::lonnet::allowed('mgr',$tmp_courseid);
+    my $allowed=&Apache::lonnet::allowed('vgr',$tmp_courseid);
     if ($allowed) {
       $symb=$ENV{'form.grade_symb'};
       $courseid=$ENV{'form.grade_courseid'};
@@ -1391,12 +1496,22 @@ sub whichuser {
       $name=$ENV{'form.grade_username'};
     }
   } else {
-    $symb=&Apache::lonnet::symbread();
-    $courseid=$ENV{'request.course.id'};
-    $domain=$ENV{'user.domain'};
-    $name=$ENV{'user.name'};
+      if (!$passedsymb) {
+          $symb=&Apache::lonnet::symbread();
+      } else {
+          $symb=$passedsymb;
+      }
+      $courseid=$ENV{'request.course.id'};
+      $domain=$ENV{'user.domain'};
+      $name=$ENV{'user.name'};
+      if ($name eq 'public' && $domain eq 'public') {
+	  if (!defined($ENV{'form.username'})) {
+	      $ENV{'form.username'}.=time.rand(10000000);
+	  }
+	  $name.=$ENV{'form.username'};
+      }
   }
-  return ($symb,$courseid,$domain,$name);
+  return ($symb,$courseid,$domain,$name,$publicuser);
 }
 
 1;