--- loncom/xml/lonxml.pm	2004/03/19 22:06:53	1.312
+++ loncom/xml/lonxml.pm	2004/08/29 08:17:22	1.332.2.1
@@ -1,7 +1,7 @@
 # The LearningOnline Network with CAPA
 # XML Parser Module 
 #
-# $Id: lonxml.pm,v 1.312 2004/03/19 22:06:53 albertel Exp $
+# $Id: lonxml.pm,v 1.332.2.1 2004/08/29 08:17:22 albertel Exp $
 #
 # Copyright Michigan State University Board of Trustees
 #
@@ -36,30 +36,11 @@
 # The C source of the Code may not be distributed by the Licensee
 # to any other parties under any circumstances.
 #
-# last modified 06/26/00 by Alexander Sakharuk
-# 11/6 Gerd Kortemeyer
-# 6/1/1 Gerd Kortemeyer
-# 2/21,3/13 Guy
-# 3/29,5/4 Gerd Kortemeyer
-# 5/26 Gerd Kortemeyer
-# 5/27 H. K. Ng
-# 6/2,6/3,6/8,6/9 Gerd Kortemeyer
-# 6/12,6/13 H. K. Ng
-# 6/16 Gerd Kortemeyer
-# 7/27 H. K. Ng
-# 8/7,8/9,8/10,8/11,8/15,8/16,8/17,8/18,8/20,8/23,8/24 Gerd Kortemeyer
-# Guy Albertelli
-# 9/26 Gerd Kortemeyer
-# Dec Guy Albertelli
-# YEAR=2002
-# 1/1 Gerd Kortemeyer
-# 1/2 Matthew Hall
-# 1/3 Gerd Kortemeyer
-#
+
 
 package Apache::lonxml; 
 use vars 
-qw(@pwd @outputstack $redirection $import @extlinks $metamode $evaluate %insertlist @namespace $prevent_entity_encode $errorcount $warningcount);
+qw(@pwd @outputstack $redirection $import @extlinks $metamode $evaluate %insertlist @namespace $errorcount $warningcount @htmlareafields);
 use strict;
 use HTML::LCParser();
 use HTML::TreeBuilder();
@@ -141,9 +122,6 @@ $evaluate = 1;
 # stores the list of active tag namespaces
 @namespace=();
 
-# if 0 all high ASCII characters will be encoded into HTML Entities
-$prevent_entity_encode=0;
-
 # has the dynamic menu been updated to know about this resource
 $Apache::lonxml::registered=0;
 
@@ -172,6 +150,7 @@ $Apache::lonxml::warnings_error_header='
 
 sub xmlbegin {
   my $output='';
+  @htmlareafields=();
   if ($ENV{'browser.mathml'}) {
       $output='<?xml version="1.0"?>'
             .'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'
@@ -409,16 +388,19 @@ sub latex_special_symbols {
         $string=~s/([^\\])\#/$1\\\#/g;
     } else {
 	$string=~s/\\/\\ensuremath{\\backslash}/g;
-	$string=~s/([^\\])\%/$1\\\%/g;
-	$string=~s/([^\\])(\$|_)/$1\\$2/g;
+	$string=~s/([^\\]|^)\%/$1\\\%/g;
+	$string=~s/([^\\]|^)\$/$1\\\$/g;
+	$string=~s/([^\\])\_/$1\\_/g;
 	$string=~s/\$\$/\$\\\$/g;
+	$string=~s/\_\_/\_\\\_/g;
 	$string=~s/\#\#/\#\\\#/g;
-        $string=~s/([^\\])(\~|\^)/$1\\$2\\strut /g;
+        $string=~s/([^\\]|^)(\~|\^)/$1\\$2\\strut /g;
 	$string=~s/(>|<)/\\ensuremath\{$1\}/g; #more or less
 	$string=&Apache::lonprintout::character_chart($string);
 	# any & or # leftover should be safe to just escape
-        $string=~s/([^\\])\&/$1\\\&/g;
-        $string=~s/([^\\])\#/$1\\\#/g;
+        $string=~s/([^\\]|^)\&/$1\\\&/g;
+        $string=~s/([^\\]|^)\#/$1\\\#/g;
+        $string=~s/\|/\$\\mid\$/g;
 #single { or } How to escape?
     }
     return $string;
@@ -482,7 +464,7 @@ sub inner_xmlparse {
 	    #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) {
+		if ($token->[1] =~ /^\Q$lasttag\E$/i) {
 		    &Apache::lonxml::warning('Using tag &lt;/'.$token->[1].'&gt; on line '.$token->[3].' as end tag to &lt;'.$$stack[-1].'&gt;');
 		    last;
 		} else {
@@ -517,10 +499,6 @@ sub inner_xmlparse {
 	  }
       }
 
-      # Encode any high ASCII characters
-#      if (!$Apache::lonxml::prevent_entity_encode) {
-#	$result=&HTML::Entities::encode($result,"\200-\377");
-#      }
       if ($Apache::lonxml::redirection) {
 	$Apache::lonxml::outputstack['-1'] .= $result;
       } else {
@@ -550,6 +528,10 @@ sub inner_xmlparse {
   return $finaloutput;
 }
 
+## 
+## Looks to see if there is a subroutine defined for this tag.  If so, call it,
+## otherwise do not call it as we do not know what it is.
+##
 sub callsub {
   my ($sub,$target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
   my $currentstring='';
@@ -582,6 +564,10 @@ sub callsub {
 					     $parstack,$parser,$safeeval,
 					     $style);
       } else {
+          if ($target eq 'tex') {
+              # throw away tag name
+              return '';
+          }
 	#&Apache::lonxml::debug("NOT Calling sub $sub in $space $metamode");
 	if ($metamode <1) {
 	  if (defined($token->[4]) && ($metamode < 1)) {
@@ -622,6 +608,7 @@ sub setup_globals {
   my ($request,$target)=@_;
   $Apache::lonxml::request=$request;
   $Apache::lonxml::registered = 0;
+  @Apache::lonxml::htmlareafields=();
   $errorcount=0;
   $warningcount=0;
   $Apache::lonxml::default_homework_loaded=0;
@@ -680,7 +667,9 @@ sub init_safespace {
   $safehole->wrap(\&Apache::scripttag::xmlparse,$safeeval,'&xmlparse');
   $safehole->wrap(\&Apache::outputtags::multipart,$safeeval,'&multipart');
   $safehole->wrap(\&Apache::lonnet::EXT,$safeeval,'&EXT');
-  
+  $safehole->wrap(\&Apache::chemresponse::chem_standard_order,$safeeval,
+		  '&chem_standard_order');
+
   $safehole->wrap(\&Math::Cephes::asin,$safeeval,'&asin');
   $safehole->wrap(\&Math::Cephes::acos,$safeeval,'&acos');
   $safehole->wrap(\&Math::Cephes::atan,$safeeval,'&atan');
@@ -754,38 +743,19 @@ sub init_safespace {
   $safehole->wrap(\&Math::Random::random_set_seed,$safeeval,'&random_set_seed');
   $safehole->wrap(\&Apache::lonxml::error,$safeeval,'&LONCAPA_INTERNAL_ERROR');
   $safehole->wrap(\&Apache::lonxml::debug,$safeeval,'&LONCAPA_INTERNAL_DEBUG');
+  $safehole->wrap(\&Apache::caparesponse::get_sigrange,$safeeval,'&LONCAPA_INTERNAL_get_sigrange');
 
 #need to inspect this class of ops
 # $safeeval->deny(":base_orig");
+  $safeeval->permit("require");
   $safeinit .= ';$external::target="'.$target.'";';
   my $rndseed;
   my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
   $rndseed=&Apache::lonnet::rndseed($symb,$courseid,$domain,$name);
-  $safeinit .= ';$external::randomseed='.$rndseed.';';
+  $safeinit .= ';$external::randomseed="'.$rndseed.'";';
   &Apache::lonxml::debug("Setting rndseed to $rndseed");
   &Apache::run::run($safeinit,$safeeval);
 
-  my $subroutine=<<'EVALUATESUB';
-sub __LC_INTERNAL_EVALUATE__ {
-    my ($__LC__a,$__LC__b,$__LC__c)=@_;
-    my $__LC__prefix;
-    while(1){
-	{ 
-	    use strict;
-	    no strict "vars";
-	    if (eval(defined(eval($__LC__a.$__LC__b)))) {
-		return $__LC__prefix.eval($__LC__a.$__LC__b.$__LC__c);
-	    }
-	}
-	$__LC__prefix.=substr($__LC__a,0,1,"");
-	if ($__LC__a!~/^(\$|&|\#)/) { last; }
-    }
-    return $__LC__prefix.$__LC__a.$__LC__b.$__LC__c;
-}
-EVALUATESUB
-    $safeeval->permit("require");
-    $safeeval->reval($subroutine);
-    $safeeval->deny("require");
 }
 
 sub default_homework_load {
@@ -800,18 +770,26 @@ sub default_homework_load {
     }
 }
 
+my $metamode_was;
 sub startredirection {
-  $Apache::lonxml::redirection++;
-  push (@Apache::lonxml::outputstack, '');
+    if (!$Apache::lonxml::redirection) {
+	$metamode_was=$Apache::lonxml::metamode;
+    }
+    $Apache::lonxml::metamode=0;
+    $Apache::lonxml::redirection++;
+    push (@Apache::lonxml::outputstack, '');
 }
 
 sub endredirection {
-  if (!$Apache::lonxml::redirection) {
-    &Apache::lonxml::error("Endredirection was called, before a startredirection, perhaps you have unbalanced tags. Some debuging information:".join ":",caller);
-    return '';
-  }
-  $Apache::lonxml::redirection--;
-  pop @Apache::lonxml::outputstack;
+    if (!$Apache::lonxml::redirection) {
+	&Apache::lonxml::error("Endredirection was called, before a startredirection, perhaps you have unbalanced tags. Some debuging information:".join ":",caller);
+	return '';
+    }
+    $Apache::lonxml::redirection--;
+    if (!$Apache::lonxml::redirection) {
+	$Apache::lonxml::metamode=$metamode_was;
+    }
+    pop @Apache::lonxml::outputstack;
 }
 
 sub end_tag {
@@ -857,30 +835,30 @@ sub decreasedepth {
 
 sub get_all_text_unbalanced {
 #there is a copy of this in lonpublisher.pm
- my($tag,$pars)= @_;
- my $token;
- my $result='';
- $tag='<'.$tag.'>';
- while ($token = $$pars[-1]->get_token) {
-   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') {
-     $result.=$token->[4];
-   } elsif ($token->[0] eq 'E')  {
-     $result.=$token->[2];
-   }
-   if ($result =~ /(.*)\Q$tag\E(.*)/s) {
-     &Apache::lonxml::debug('Got a winner with leftovers ::'.$2);
-     &Apache::lonxml::debug('Result is :'.$1);
-     $result=$1;
-     my $redo=$tag.$2;
-     &Apache::lonxml::newparser($pars,\$redo);
-     last;
-   }
- }
- return $result
+    my($tag,$pars)= @_;
+    my $token;
+    my $result='';
+    $tag='<'.$tag.'>';
+    while ($token = $$pars[-1]->get_token) {
+	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') {
+	    $result.=$token->[4];
+	} elsif ($token->[0] eq 'E')  {
+	    $result.=$token->[2];
+	}
+	if ($result =~ /\Q$tag\E/is) {
+	    ($result,my $redo)=$result =~ /(.*)\Q$tag\E(.*)/is;
+	    #&Apache::lonxml::debug('Got a winner with leftovers ::'.$2);
+	    #&Apache::lonxml::debug('Result is :'.$1);
+	    $redo=$tag.$redo;
+	    &Apache::lonxml::newparser($pars,\$redo);
+	    last;
+	}
+    }
+    return $result
 }
 
 sub increment_counter {
@@ -933,12 +911,12 @@ sub get_all_text {
 		} 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; }
+		    if ($token->[1] =~ /^\Q$tag\E$/i) { $depth++; }
+		    if ($token->[1] =~ /^LONCAPA_INTERNAL_TURN_STYLE_ON$/) { $Apache::lonxml::usestyle=1; }
+		    if ($token->[1] =~ /^LONCAPA_INTERNAL_TURN_STYLE_OFF$/) { $Apache::lonxml::usestyle=0; }
 		    $result.=$token->[4];
 		} elsif ($token->[0] eq 'E')  {
-		    if ( $token->[1] =~ /^$tag$/i) { $depth--; }
+		    if ( $token->[1] =~ /^\Q$tag\E$/i) { $depth--; }
 		    #skip sending back the last end tag
 		    if ($depth == 0 && exists($$style{'/'.$token->[1]}) && $Apache::lonxml::usestyle) {
 			my $string=
@@ -967,7 +945,7 @@ sub get_all_text {
 	    #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).
+		   &HTML::Entities::encode($result,'<>&"').
 		   '</pre>');
 	    if ($gotfullstack) {
 		my $newstring='</'.$tag.'>'.$result;
@@ -985,13 +963,13 @@ sub get_all_text {
 		} elsif ($token->[0] eq 'PI') {
 		    $result.=$token->[2];
 		} elsif ($token->[0] eq 'S') {
-		    if ( $token->[1] =~ /^$tag$/i) {
+		    if ( $token->[1] =~ /^\Q$tag\E$/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; }
+		    if ($token->[1] =~ /^LONCAPA_INTERNAL_TURN_STYLE_ON$/) { $Apache::lonxml::usestyle=1; }
+		    if ($token->[1] =~ /^LONCAPA_INTERNAL_TURN_STYLE_OFF$/) { $Apache::lonxml::usestyle=0; }
 		} elsif ($token->[0] eq 'E')  {
 		    $result.=$token->[2];
 		}
@@ -1073,7 +1051,7 @@ sub afterburn {
            my $anchorname=$_;
 	   my $matchthis=$anchorname;
            $matchthis=~s/\_+/\\s\+/g;
-           $result=~s/($matchthis)/\<font color=\"red\"\>$1\<\/font\>/gs;
+           $result=~s/(\Q$matchthis\E)/\<font color=\"red\"\>$1\<\/font\>/gs;
        }
     }
     if ($ENV{'form.link'}) {
@@ -1081,14 +1059,14 @@ sub afterburn {
            my ($anchorname,$linkurl)=split(/\>/,$_);
 	   my $matchthis=$anchorname;
            $matchthis=~s/\_+/\\s\+/g;
-           $result=~s/($matchthis)/\<a href=\"$linkurl\"\>$1\<\/a\>/gs;
+           $result=~s/(\Q$matchthis\E)/\<a href=\"$linkurl\"\>$1\<\/a\>/gs;
        }
     }
     if ($ENV{'form.anchor'}) {
         my $anchorname=$ENV{'form.anchor'};
 	my $matchthis=$anchorname;
         $matchthis=~s/\_+/\\s\+/g;
-        $result=~s/($matchthis)/\<a name=\"$anchorname\"\>$1\<\/a\>/s;
+        $result=~s/(\Q$matchthis\E)/\<a name=\"$anchorname\"\>$1\<\/a\>/s;
         $result.=(<<"ENDSCRIPT");
 <script type="text/javascript">
     document.location.hash='$anchorname';
@@ -1112,21 +1090,20 @@ sub storefile {
 }
 
 sub createnewhtml {
-  my $filecontents=(<<SIMPLECONTENT);
+    my $title=&mt('Title of document goes here');
+    my $body=&mt('Body of document goes here');
+    my $filecontents=(<<SIMPLECONTENT);
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml/11/DTD/xhtml11.dtd">
 <html>
 <head>
-<title>
-                           Title of Document Goes Here
-</title>
+<title>$title</title>
 </head>
 <body bgcolor="#FFFFFF">
-
-                           Body of Document Goes Here
-
+$body
 </body>
 </html>
 SIMPLECONTENT
-  return $filecontents;
+    return $filecontents;
 }
 
 sub createnewsty {
@@ -1144,11 +1121,27 @@ SIMPLECONTENT
 
 sub inserteditinfo {
       my ($result,$filecontents,$filetype)=@_;
-      $filecontents = &HTML::Entities::encode($filecontents);
+      $filecontents = &HTML::Entities::encode($filecontents,'<>&"');
 #      my $editheader='<a href="#editsection">Edit below</a><hr />';
       my $xml_help = '';
+      my $initialize='';
       if ($filetype eq 'html') {
-	  $xml_help=Apache::loncommon::helpLatexCheatsheet();
+	  my $addbuttons=&Apache::lonhtmlcommon::htmlareaaddbuttons();
+	  $initialize=&Apache::lonhtmlcommon::htmlareaheaders().(<<FULLPAGE);
+<script type="text/javascript">
+$addbuttons
+
+    HTMLArea.loadPlugin("FullPage");
+
+    function initDocument() {
+	var editor=new HTMLArea("filecont",config);
+	editor.registerPlugin(FullPage);
+	editor.generate();
+    }
+</script>
+FULLPAGE
+          $result=~s/\<body([^\>]*)\>/\<body onload="initDocument()" $1\>/i;
+	  $xml_help=&Apache::loncommon::helpLatexCheatsheet();
       }
       my $cleanbut = '';
       if ($filetype eq 'html') {
@@ -1164,18 +1157,21 @@ $cleanbut
 <input type="submit" name="savethisfile" accesskey="s"  value="$lt{'st'}" />
 <input type="submit" name="viewmode" accesskey="v" value="$lt{'vi'}" />
 BUTTONS
+      $buttons.=&Apache::lonhtmlcommon::htmlareaselectactive('filecont');
       my $editfooter=(<<ENDFOOTER);
+$initialize
 <hr />
 <a name="editsection" />
 <form method="post">
 $xml_help
 <input type="hidden" name="editmode" value="$lt{'ed'}" />
 $buttons<br />
-<textarea cols="80" rows="40" name="filecont">$filecontents</textarea>
+<textarea cols="80" rows="44" name="filecont" id="filecont">$filecontents</textarea>
 <br />$buttons
 <br />
 </form>
 $titledisplay
+</body>
 ENDFOOTER
 #      $result=~s/(\<body[^\>]*\>)/$1$editheader/is;
       $result=~s/(\<\/body\>)/$editfooter/is;
@@ -1329,7 +1325,8 @@ sub debug {
 	$|=1;
 	my $request=$Apache::lonxml::request;
 	if (!$request) { $request=Apache->request; }
-	$request->print('<font size="-2"><pre>DEBUG:'.&HTML::Entities::encode($_[0])."</pre></font>\n");
+	$request->print('<font size="-2"><pre>DEBUG:'.&HTML::Entities::encode($_[0],'<>&"')."</pre></font>\n");
+#	&Apache::lonnet::logthis($_[0]);
     }
 }