File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.372: download - view: text, annotated - select for diffs
Thu Apr 7 06:56:27 2005 UTC (19 years, 1 month ago) by albertel
Branches: MAIN
CVS tags: version_1_99_0_tmcc, HEAD
- ENV -> env

    1: # The LearningOnline Network with CAPA
    2: # XML Parser Module 
    3: #
    4: # $Id: lonxml.pm,v 1.372 2005/04/07 06:56:27 albertel Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: # Copyright for TtHfunc and TtMfunc by Ian Hutchinson. 
   29: # TtHfunc and TtMfunc (the "Code") may be compiled and linked into 
   30: # binary executable programs or libraries distributed by the 
   31: # Michigan State University (the "Licensee"), but any binaries so 
   32: # distributed are hereby licensed only for use in the context
   33: # of a program or computational system for which the Licensee is the 
   34: # primary author or distributor, and which performs substantial 
   35: # additional tasks beyond the translation of (La)TeX into HTML.
   36: # The C source of the Code may not be distributed by the Licensee
   37: # to any other parties under any circumstances.
   38: #
   39: 
   40: 
   41: package Apache::lonxml; 
   42: use vars 
   43: qw(@pwd @outputstack $redirection $import @extlinks $metamode $evaluate %insertlist @namespace $errorcount $warningcount @htmlareafields);
   44: use strict;
   45: use HTML::LCParser();
   46: use HTML::TreeBuilder();
   47: use HTML::Entities();
   48: use Safe();
   49: use Safe::Hole();
   50: use Math::Cephes();
   51: use Math::Random();
   52: use Opcode();
   53: use POSIX qw(strftime);
   54: use Time::HiRes qw( gettimeofday tv_interval );
   55: 
   56: sub register {
   57:   my ($space,@taglist) = @_;
   58:   foreach my $temptag (@taglist) {
   59:     push(@{ $Apache::lonxml::alltags{$temptag} },$space);
   60:   }
   61: }
   62: 
   63: sub deregister {
   64:   my ($space,@taglist) = @_;
   65:   foreach my $temptag (@taglist) {
   66:     my $tempspace = $Apache::lonxml::alltags{$temptag}[-1];
   67:     if ($tempspace eq $space) {
   68:       pop(@{ $Apache::lonxml::alltags{$temptag} });
   69:     }
   70:   }
   71:   #&printalltags();
   72: }
   73: 
   74: use Apache::Constants qw(:common);
   75: use Apache::lontexconvert();
   76: use Apache::style();
   77: use Apache::run();
   78: use Apache::londefdef();
   79: use Apache::scripttag();
   80: use Apache::languagetags();
   81: use Apache::edit();
   82: use Apache::inputtags();
   83: use Apache::outputtags();
   84: use Apache::lonnet;
   85: use Apache::File();
   86: use Apache::loncommon();
   87: use Apache::lonfeedback();
   88: use Apache::lonmsg();
   89: use Apache::loncacc();
   90: use Apache::lonlocal;
   91: 
   92: #==================================================   Main subroutine: xmlparse  
   93: #debugging control, to turn on debugging modify the correct handler
   94: $Apache::lonxml::debug=0;
   95: 
   96: # keeps count of the number of warnings and errors generated in a parse
   97: $warningcount=0;
   98: $errorcount=0;
   99: 
  100: #path to the directory containing the file currently being processed
  101: @pwd=();
  102: 
  103: #these two are used for capturing a subset of the output for later processing,
  104: #don't touch them directly use &startredirection and &endredirection
  105: @outputstack = ();
  106: $redirection = 0;
  107: 
  108: #controls wheter the <import> tag actually does
  109: $import = 1;
  110: @extlinks=();
  111: 
  112: # meta mode is a bit weird only some output is to be turned off
  113: #<output> tag turns metamode off (defined in londefdef.pm)
  114: $metamode = 0;
  115: 
  116: # turns on and of run::evaluate actually derefencing var refs
  117: $evaluate = 1;
  118: 
  119: # data structure for eidt mode, determines what tags can go into what other tags
  120: %insertlist=();
  121: 
  122: # stores the list of active tag namespaces
  123: @namespace=();
  124: 
  125: # has the dynamic menu been updated to know about this resource
  126: $Apache::lonxml::registered=0;
  127: 
  128: # a pointer the the Apache request object
  129: $Apache::lonxml::request='';
  130: 
  131: # a problem number counter, and check on ether it is used
  132: $Apache::lonxml::counter=1;
  133: $Apache::lonxml::counter_changed=0;
  134: 
  135: #internal check on whether to look at style defs
  136: $Apache::lonxml::usestyle=1;
  137: 
  138: #locations used to store the parameter string for style substitutions
  139: $Apache::lonxml::style_values='';
  140: $Apache::lonxml::style_end_values='';
  141: 
  142: #array of ssi calls that need to occur after we are done parsing
  143: @Apache::lonxml::ssi_info=();
  144: 
  145: #should we do the postag variable interpolation
  146: $Apache::lonxml::post_evaluate=1;
  147: 
  148: #a header message to emit in the case of any generated warning or errors
  149: $Apache::lonxml::warnings_error_header='';
  150: 
  151: sub xmlbegin {
  152:     my ($style)=@_;
  153:     my $output='';
  154:     @htmlareafields=();
  155:     if ($env{'browser.mathml'}) {
  156: 	$output='<?xml version="1.0"?>'
  157:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
  158: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
  159:             
  160: #	    .'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" [<!ENTITY mathns "http://www.w3.org/1998/Math/MathML">] >'
  161: 	    .'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1 plus MathML 2.0 plus SVG 1.1//EN" "http://www.w3.org/2002/04/xhtml-math-svg/xhtml-math-svg.dtd">'
  162:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
  163: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
  164:     } else {
  165: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>';
  166:     }
  167:     if ($style eq 'encode') {
  168: 	$output=&HTML::Entities::encode($output,'<>&"');
  169:     }
  170:     return $output;
  171: }
  172: 
  173: sub xmlend {
  174:     my ($target,$parser)=@_;
  175:     my $mode='xml';
  176:     my $status='OPEN';
  177:     if ($Apache::lonhomework::parsing_a_problem ||
  178: 	$Apache::lonhomework::parsing_a_task ) {
  179: 	$mode='problem';
  180: 	$status=$Apache::inputtags::status[-1]; 
  181:     }
  182:     my $discussion;
  183:     &Apache::loncommon::get_unprocessed_cgi
  184:         ($env{'query_string'},['LONCAPA_INTERNAL_no_discussion']);
  185:     if (! exists($env{'form.LONCAPA_INTERNAL_no_discussion'}) ||
  186:         $env{'form.LONCAPA_INTERNAL_no_discussion'} ne 'true') {
  187:         $discussion=&Apache::lonfeedback::list_discussion($mode,$status);
  188:     }
  189:     if ($target eq 'tex') {
  190: 	$discussion.='<tex>\keephidden{ENDOFPROBLEM}\vskip 0.5mm\noindent\makebox[\textwidth/$number_of_columns][b]{\hrulefill}\end{document}</tex>';
  191: 	&Apache::lonxml::newparser($parser,\$discussion,'');
  192: 	return '';
  193:     } else {
  194: 	return $discussion.&Apache::loncommon::endbodytag();
  195:     }
  196: }
  197: 
  198: sub tokeninputfield {
  199:     my $defhost=$Apache::lonnet::perlvar{'lonHostID'};
  200:     $defhost=~tr/a-z/A-Z/;
  201:     return (<<ENDINPUTFIELD)
  202: <script type="text/javascript">
  203:     function updatetoken() {
  204: 	var comp=new Array;
  205:         var barcode=unescape(document.tokeninput.barcode.value);
  206:         comp=barcode.split('*');
  207:         if (typeof(comp[0])!="undefined") {
  208: 	    document.tokeninput.codeone.value=comp[0];
  209: 	}
  210:         if (typeof(comp[1])!="undefined") {
  211: 	    document.tokeninput.codetwo.value=comp[1];
  212: 	}
  213:         if (typeof(comp[2])!="undefined") {
  214:             comp[2]=comp[2].toUpperCase();
  215: 	    document.tokeninput.codethree.value=comp[2];
  216: 	}
  217:         document.tokeninput.barcode.value='';
  218:     }  
  219: </script>
  220: <form method="post" name="tokeninput">
  221: <table border="2" bgcolor="#FFFFBB">
  222: <tr><th>DocID Checkin</th></tr>
  223: <tr><td>
  224: <table>
  225: <tr>
  226: <td>Scan in Barcode</td>
  227: <td><input type="text" size="22" name="barcode" 
  228: onChange="updatetoken()"/></td>
  229: </tr>
  230: <tr><td><i>or</i> Type in DocID</td>
  231: <td>
  232: <input type="text" size="5" name="codeone" />
  233: <b><font size="+2">*</font></b>
  234: <input type="text" size="5" name="codetwo" />
  235: <b><font size="+2">*</font></b>
  236: <input type="text" size="10" name="codethree" value="$defhost" 
  237: onChange="this.value=this.value.toUpperCase()" />
  238: </td></tr>
  239: </table>
  240: </td></tr>
  241: <tr><td><input type="submit" value="Check in DocID" /></td></tr>
  242: </table>
  243: </form>
  244: ENDINPUTFIELD
  245: }
  246: 
  247: sub maketoken {
  248:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
  249:     unless ($symb) {
  250: 	$symb=&Apache::lonnet::symbread();
  251:     }
  252:     unless ($tuname) {
  253: 	$tuname=$env{'user.name'};
  254:         $tudom=$env{'user.domain'};
  255:         $tcrsid=$env{'request.course.id'};
  256:     }
  257: 
  258:     return &Apache::lonnet::checkout($symb,$tuname,$tudom,$tcrsid);
  259: }
  260: 
  261: sub printtokenheader {
  262:     my ($target,$token,$tsymb,$tcrsid,$tudom,$tuname)=@_;
  263:     unless ($token) { return ''; }
  264: 
  265:     my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
  266:     unless ($tsymb) {
  267: 	$tsymb=$symb;
  268:     }
  269:     unless ($tuname) {
  270: 	$tuname=$name;
  271:         $tudom=$domain;
  272:         $tcrsid=$courseid;
  273:     }
  274: 
  275:     my %reply=&Apache::lonnet::get('environment',
  276:               ['firstname','middlename','lastname','generation'],
  277:               $tudom,$tuname);
  278:     my $plainname=$reply{'firstname'}.' '. 
  279:                   $reply{'middlename'}.' '.
  280:                   $reply{'lastname'}.' '.
  281: 		  $reply{'generation'};
  282: 
  283:     if ($target eq 'web') {
  284:         my %idhash=&Apache::lonnet::idrget($tudom,($tuname));
  285: 	return 
  286:  '<img align="right" src="/cgi-bin/barcode.png?encode='.$token.'" />'.
  287:                &mt('Checked out for').' '.$plainname.
  288:                '<br />'.&mt('User').': '.$tuname.' at '.$tudom.
  289: 	       '<br />'.&mt('ID').': '.$idhash{$tuname}.
  290: 	       '<br />'.&mt('CourseID').': '.$tcrsid.
  291: 	       '<br />'.&mt('Course').': '.$env{'course.'.$tcrsid.'.description'}.
  292:                '<br />'.&mt('DocID').': '.$token.
  293:                '<br />'.&mt('Time').': '.&Apache::lonlocal::locallocaltime().'<hr />';
  294:     } else {
  295:         return $token;
  296:     }
  297: }
  298: 
  299: sub fontsettings {
  300:     my $headerstring='';
  301:     if (($env{'browser.os'} eq 'mac') && (!$env{'browser.mathml'})) { 
  302: 	$headerstring.=
  303: 	    '<meta Content-Type="text/html; charset=x-mac-roman" />';
  304:     } elsif (!$env{'browser.mathml'} && $env{'browser.unicode'}) {
  305: 	$headerstring.=
  306: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
  307:     }
  308:     return $headerstring;
  309: }
  310: 
  311: sub printalltags {
  312:   my $temp;
  313:   foreach $temp (sort keys %Apache::lonxml::alltags) {
  314:     &Apache::lonxml::debug("$temp -- ".
  315: 		  join(',',@{ $Apache::lonxml::alltags{$temp} }));
  316:   }
  317: }
  318: 
  319: sub xmlparse {
  320:  my ($request,$target,$content_file_string,$safeinit,%style_for_target) = @_;
  321: 
  322:  &setup_globals($request,$target);
  323:  &Apache::inputtags::initialize_inputtags();
  324:  &Apache::bridgetask::initialize_bridgetask();
  325:  &Apache::outputtags::initialize_outputtags();
  326:  &Apache::edit::initialize_edit();
  327:  &Apache::londefdef::initialize_londefdef();
  328: 
  329: #
  330: # do we have a course style file?
  331: #
  332: 
  333:  if ($env{'request.course.id'} && $env{'request.state'} ne 'construct') {
  334:      my $bodytext=
  335: 	 $env{'course.'.$env{'request.course.id'}.'.default_xml_style'};
  336:      if ($bodytext) {
  337: 	 foreach my $file (split(',',$bodytext)) {
  338: 	     my $location=&Apache::lonnet::filelocation('',$file);
  339: 	     my $styletext=&Apache::lonnet::getfile($location);
  340: 	     if ($styletext ne '-1') {
  341: 		 %style_for_target = (%style_for_target,
  342: 				      &Apache::style::styleparser($target,$styletext));
  343: 	     }
  344: 	 }
  345:      }
  346:  } elsif ($env{'construct.style'} && ($env{'request.state'} eq 'construct')) {
  347:      my $location=&Apache::lonnet::filelocation('',$env{'construct.style'});
  348:      my $styletext=&Apache::lonnet::getfile($location);
  349:        if ($styletext ne '-1') {
  350:           %style_for_target = (%style_for_target,
  351:                           &Apache::style::styleparser($target,$styletext));
  352:       }
  353:  }
  354: #&printalltags();
  355:  my @pars = ();
  356:  my $pwd=$env{'request.filename'};
  357:  $pwd =~ s:/[^/]*$::;
  358:  &newparser(\@pars,\$content_file_string,$pwd);
  359: 
  360:  my $safeeval = new Safe;
  361:  my $safehole = new Safe::Hole;
  362:  &init_safespace($target,$safeeval,$safehole,$safeinit);
  363: #-------------------- Redefinition of the target in the case of compound target
  364: 
  365:  ($target, my @tenta) = split('&&',$target);
  366: 
  367:  my @stack = ();
  368:  my @parstack = ();
  369:  &initdepth();
  370:  &init_alarm();
  371:  my $finaloutput = &inner_xmlparse($target,\@stack,\@parstack,\@pars,
  372: 				   $safeeval,\%style_for_target);
  373: 
  374:  if ($env{'request.uri'}) {
  375:     &writeallows($env{'request.uri'});
  376:  }
  377:  &do_registered_ssi();
  378:  if ($Apache::lonxml::counter_changed) { &store_counter() }
  379:  if ($env{'form.return_only_error_and_warning_counts'}) {
  380:      return "$errorcount:$warningcount";
  381:  }
  382:  return $finaloutput;
  383: }
  384: 
  385: sub htmlclean {
  386:     my ($raw,$full)=@_;
  387: # Take care of CRLF etc
  388: 
  389:     $raw=~s/\r\f/\n/gs; $raw=~s/\f\r/\n/gs;
  390:     $raw=~s/\r\n/\n/gs; $raw=~s/\n\r/\n/gs;
  391:     $raw=~s/\f/\n/gs; $raw=~s/\r/\n/gs;
  392:     $raw=~s/\&\#10\;/\n/gs; $raw=~s/\&\#13\;/\n/gs;
  393: 
  394: # Generate empty tags, remove wrong end tags
  395:     $raw=~s/\<(br|hr|img|meta|allow|basefont)([^\>\/]*?)\>/\<$1$2 \/\>/gis;
  396:     $raw=~s/\<\/(br|hr|img|meta|allow|basefont)\>//gis;
  397:     unless ($full) {
  398:        $raw=~s/\<[\/]*(body|head|html)\>//gis;
  399:     }
  400: # Make standard tags lowercase
  401:     foreach ('html','body','head','meta','h1','h2','h3','h4','b','i','m',
  402:              'table','tr','td','th','p','br','hr','img','embed','font',
  403:              'a','strong','center','title','basefont','li','ol','ul',
  404:              'input','select','form','option','script','pre') {
  405: 	$raw=~s/\<$_\s*\>/\<$_\>/gis;
  406:         $raw=~s/\<\/$_\s*\>/<\/$_\>/gis;
  407:         $raw=~s/\<$_\s([^\>]*)\>/<$_ $1\>/gis;
  408:     }
  409:     return $raw;
  410: }
  411: 
  412: sub latex_special_symbols {
  413:     my ($string,$where)=@_;
  414:     if ($where eq 'header') {
  415: 	$string =~ s/(\\|_|\^)/ /g;
  416: 	$string =~ s/(\$|%|\{|\})/\\$1/g;
  417: 	$string =~ s/_/ /g;
  418: 	$string=&Apache::lonprintout::character_chart($string);
  419: 	# any & or # leftover should be safe to just escape
  420:         $string=~s/([^\\])\&/$1\\\&/g;
  421:         $string=~s/([^\\])\#/$1\\\#/g;
  422:     } else {
  423: 	$string=~s/\\/\\ensuremath{\\backslash}/g;
  424: 	$string=~s/\\\%|\%/\\\%/g;
  425: 	$string=~s/\\{|{/\\{/g;
  426: 	$string=~s/\\}|}/\\}/g;
  427: 	$string=~s/\\\$|\$/\\\$/g;
  428: 	$string=~s/\\\_|\_/\\\_/g;
  429:         $string=~s/([^\\]|^)(\~|\^)/$1\\$2\\strut /g;
  430: 	$string=~s/(>|<)/\\ensuremath\{$1\}/g; #more or less
  431: 	$string=&Apache::lonprintout::character_chart($string);
  432: 	# any & or # leftover should be safe to just escape
  433: 	$string=~s/\\\&|\&/\\\&/g;
  434: 	$string=~s/\\\#|\#/\\\#/g;
  435:         $string=~s/\|/\$\\mid\$/g;
  436: #single { or } How to escape?
  437:     }
  438:     return $string;
  439: }
  440: 
  441: sub inner_xmlparse {
  442:   my ($target,$stack,$parstack,$pars,$safeeval,$style_for_target)=@_;
  443:   my $finaloutput = '';
  444:   my $result;
  445:   my $token;
  446:   my $dontpop=0;
  447:   while ( $#$pars > -1 ) {
  448:     while ($token = $$pars['-1']->get_token) {
  449:       if (($token->[0] eq 'T') || ($token->[0] eq 'C') ) {
  450: 	if ($metamode<1) {
  451: 	    my $text=$token->[1];
  452: 	    if ($token->[0] eq 'C' && $target eq 'tex') {
  453: 		$text = '';
  454: #		$text = '%'.$text."\n";
  455: 	    }
  456: 	    $result.=$text;
  457: 	}
  458:       } elsif (($token->[0] eq 'D')) {
  459: 	if ($metamode<1 && $target eq 'web') {
  460: 	    my $text=$token->[1];
  461: 	    $result.=$text;
  462: 	}
  463:       } elsif ($token->[0] eq 'PI') {
  464: 	if ($metamode<1 && $target eq 'web') {
  465: 	  $result=$token->[2];
  466: 	}
  467:       } elsif ($token->[0] eq 'S') {
  468: 	# add tag to stack
  469: 	push (@$stack,$token->[1]);
  470: 	# add parameters list to another stack
  471: 	push (@$parstack,&parstring($token));
  472: 	&increasedepth($token);
  473: 	if ($Apache::lonxml::usestyle &&
  474: 	    exists($$style_for_target{$token->[1]})) {
  475: 	    $Apache::lonxml::usestyle=0;
  476: 	    my $string=$$style_for_target{$token->[1]}.
  477: 	      '<LONCAPA_INTERNAL_TURN_STYLE_ON />';
  478: 	    &Apache::lonxml::newparser($pars,\$string);
  479: 	    $Apache::lonxml::style_values=$$parstack[-1];
  480: 	    $Apache::lonxml::style_end_values=$$parstack[-1];
  481: 	} else {
  482: 	  $result = &callsub("start_$token->[1]", $target, $token, $stack,
  483: 			     $parstack, $pars, $safeeval, $style_for_target);
  484: 	}
  485:       } elsif ($token->[0] eq 'E') {
  486: 	if ($Apache::lonxml::usestyle &&
  487: 	    exists($$style_for_target{'/'."$token->[1]"})) {
  488: 	    $Apache::lonxml::usestyle=0;
  489: 	    my $string=$$style_for_target{'/'.$token->[1]}.
  490: 	      '<LONCAPA_INTERNAL_TURN_STYLE_ON end="'.$token->[1].'" />';
  491: 	    &Apache::lonxml::newparser($pars,\$string);
  492: 	    $Apache::lonxml::style_values=$Apache::lonxml::style_end_values;
  493: 	    $Apache::lonxml::style_end_values='';
  494: 	    $dontpop=1;
  495: 	} else {
  496: 	    #clear out any tags that didn't end
  497: 	    while ($token->[1] ne $$stack['-1'] && ($#$stack > -1)) {
  498: 		my $lasttag=$$stack[-1];
  499: 		if ($token->[1] =~ /^\Q$lasttag\E$/i) {
  500: 		    &Apache::lonxml::warning('Using tag &lt;/'.$token->[1].'&gt; on line '.$token->[3].' as end tag to &lt;'.$$stack[-1].'&gt;');
  501: 		    last;
  502: 		} else {
  503: 		    &Apache::lonxml::warning('Found tag &lt;/'.$token->[1].'&gt; on line '.$token->[3].' when looking for &lt;/'.$$stack[-1].'&gt; in file');
  504: 		    &end_tag($stack,$parstack,$token);
  505: 		}
  506: 	    }
  507: 	    $result = &callsub("end_$token->[1]", $target, $token, $stack,
  508: 			       $parstack, $pars,$safeeval, $style_for_target);
  509: 	}
  510:       } else {
  511: 	&Apache::lonxml::error("Unknown token event :$token->[0]:$token->[1]:");
  512:       }
  513:       #evaluate variable refs in result
  514:       if ($Apache::lonxml::post_evaluate &&$result ne "") {
  515: 	  my $extras;
  516: 	  if (!$Apache::lonxml::usestyle) {
  517: 	      $extras=$Apache::lonxml::style_values;
  518: 	  }
  519: 	if ( $#$parstack > -1 ) {
  520: 	  $result=&Apache::run::evaluate($result,$safeeval,$extras.$$parstack[-1]);
  521: 	} else {
  522: 	  $result= &Apache::run::evaluate($result,$safeeval,$extras);
  523: 	}
  524:       }
  525:       $Apache::lonxml::post_evaluate=1;
  526: 
  527:       if (($token->[0] eq 'T') || ($token->[0] eq 'C') || ($token->[0] eq 'D') ) {
  528: 	  #Style file definitions should be correct
  529: 	  if ($target eq 'tex' && ($Apache::lonxml::usestyle)) {
  530: 	      $result=&latex_special_symbols($result);
  531: 	  }
  532:       }
  533: 
  534:       if ($Apache::lonxml::redirection) {
  535: 	$Apache::lonxml::outputstack['-1'] .= $result;
  536:       } else {
  537: 	$finaloutput.=$result;
  538:       }
  539:       $result = '';
  540: 
  541:       if ($token->[0] eq 'E' && !$dontpop) {
  542: 	&end_tag($stack,$parstack,$token);
  543:       }
  544:       $dontpop=0;
  545:     }	
  546:     if ($#$pars > -1) {
  547: 	pop @$pars;
  548: 	pop @Apache::lonxml::pwd;
  549:     }
  550:   }
  551: 
  552:   # if ($target eq 'meta') {
  553:   #   $finaloutput.=&endredirection;
  554:   # }
  555: 
  556: 
  557:   if (($ENV{'QUERY_STRING'}) && ($target eq 'web')) {
  558:     $finaloutput=&afterburn($finaloutput);
  559:   }	    
  560:   return $finaloutput;
  561: }
  562: 
  563: ## 
  564: ## Looks to see if there is a subroutine defined for this tag.  If so, call it,
  565: ## otherwise do not call it as we do not know what it is.
  566: ##
  567: sub callsub {
  568:   my ($sub,$target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  569:   my $currentstring='';
  570:   my $nodefault;
  571:   {
  572:     my $sub1;
  573:     no strict 'refs';
  574:     my $tag=$token->[1];
  575: # get utterly rid of extended html tags
  576:     if ($tag=~/^x\-/i) { return ''; }
  577:     my $space=$Apache::lonxml::alltags{$tag}[-1];
  578:     if (!$space) {
  579:      	$tag=~tr/A-Z/a-z/;
  580: 	$sub=~tr/A-Z/a-z/;
  581: 	$space=$Apache::lonxml::alltags{$tag}[-1]
  582:     }
  583: 
  584:     my $deleted=0;
  585:     $Apache::lonxml::curdepth=join('_',@Apache::lonxml::depthcounter);
  586:     if (($token->[0] eq 'S') && ($target eq 'modified')) {
  587:       $deleted=&Apache::edit::handle_delete($space,$target,$token,$tagstack,
  588: 					     $parstack,$parser,$safeeval,
  589: 					     $style);
  590:     }
  591:     if (!$deleted) {
  592:       if ($space) {
  593: 	#&Apache::lonxml::debug("Calling sub $sub in $space $metamode");
  594: 	$sub1="$space\:\:$sub";
  595: 	($currentstring,$nodefault) = &$sub1($target,$token,$tagstack,
  596: 					     $parstack,$parser,$safeeval,
  597: 					     $style);
  598:       } else {
  599:           if ($target eq 'tex') {
  600:               # throw away tag name
  601:               return '';
  602:           }
  603: 	#&Apache::lonxml::debug("NOT Calling sub $sub in $space $metamode");
  604: 	if ($metamode <1) {
  605: 	  if (defined($token->[4]) && ($metamode < 1)) {
  606: 	    $currentstring = $token->[4];
  607: 	  } else {
  608: 	    $currentstring = $token->[2];
  609: 	  }
  610: 	}
  611:       }
  612:       #    &Apache::lonxml::debug("nodefalt:$nodefault:");
  613:       if ($currentstring eq '' && $nodefault eq '') {
  614: 	if ($target eq 'edit') {
  615: 	  #&Apache::lonxml::debug("doing default edit for $token->[1]");
  616: 	  if ($token->[0] eq 'S') {
  617: 	    $currentstring = &Apache::edit::tag_start($target,$token);
  618: 	  } elsif ($token->[0] eq 'E') {
  619: 	    $currentstring = &Apache::edit::tag_end($target,$token);
  620: 	  }
  621: 	} elsif ($target eq 'modified') {
  622: 	  if ($token->[0] eq 'S') {
  623: 	    $currentstring = $token->[4];
  624: 	    $currentstring.=&Apache::edit::handle_insert();
  625: 	  } elsif ($token->[0] eq 'E') {
  626: 	    $currentstring = $token->[2];
  627:             $currentstring.=&Apache::edit::handle_insertafter($token->[1]);
  628: 	  } else {
  629: 	    $currentstring = $token->[2];
  630: 	  }
  631: 	}
  632:       }
  633:     }
  634:     use strict 'refs';
  635:   }
  636:   return $currentstring;
  637: }
  638: 
  639: sub setup_globals {
  640:   my ($request,$target)=@_;
  641:   $Apache::lonxml::request=$request;
  642:   $Apache::lonxml::registered = 0;
  643:   @Apache::lonxml::htmlareafields=();
  644:   $errorcount=0;
  645:   $warningcount=0;
  646:   $Apache::lonxml::default_homework_loaded=0;
  647:   $Apache::lonxml::usestyle=1;
  648:   &init_counter();
  649:   @Apache::lonxml::pwd=();
  650:   @Apache::lonxml::extlinks=();
  651:   @Apache::lonxml::ssi_info=();
  652:   $Apache::lonxml::post_evaluate=1;
  653:   $Apache::lonxml::warnings_error_header='';
  654:   if ($target eq 'meta') {
  655:     $Apache::lonxml::redirection = 0;
  656:     $Apache::lonxml::metamode = 1;
  657:     $Apache::lonxml::evaluate = 1;
  658:     $Apache::lonxml::import = 0;
  659:   } elsif ($target eq 'answer') {
  660:     $Apache::lonxml::redirection = 0;
  661:     $Apache::lonxml::metamode = 1;
  662:     $Apache::lonxml::evaluate = 1;
  663:     $Apache::lonxml::import = 1;
  664:   } elsif ($target eq 'grade') {
  665:     &startredirection;
  666:     $Apache::lonxml::metamode = 0;
  667:     $Apache::lonxml::evaluate = 1;
  668:     $Apache::lonxml::import = 1;
  669:   } elsif ($target eq 'modified') {
  670:     $Apache::lonxml::redirection = 0;
  671:     $Apache::lonxml::metamode = 0;
  672:     $Apache::lonxml::evaluate = 0;
  673:     $Apache::lonxml::import = 0;
  674:   } elsif ($target eq 'edit') {
  675:     $Apache::lonxml::redirection = 0;
  676:     $Apache::lonxml::metamode = 0;
  677:     $Apache::lonxml::evaluate = 0;
  678:     $Apache::lonxml::import = 0;
  679:   } elsif ($target eq 'analyze') {
  680:     $Apache::lonxml::redirection = 0;
  681:     $Apache::lonxml::metamode = 0;
  682:     $Apache::lonxml::evaluate = 1;
  683:     $Apache::lonxml::import = 1;
  684:   } else {
  685:     $Apache::lonxml::redirection = 0;
  686:     $Apache::lonxml::metamode = 0;
  687:     $Apache::lonxml::evaluate = 1;
  688:     $Apache::lonxml::import = 1;
  689:   }
  690: }
  691: 
  692: sub init_safespace {
  693:   my ($target,$safeeval,$safehole,$safeinit) = @_;
  694:   $safeeval->permit("entereval");
  695:   $safeeval->permit(":base_math");
  696:   $safeeval->permit("sort");
  697:   $safeeval->permit("time");
  698:   $safeeval->deny("rand");
  699:   $safeeval->deny("srand");
  700:   $safeeval->deny(":base_io");
  701:   $safehole->wrap(\&Apache::scripttag::xmlparse,$safeeval,'&xmlparse');
  702:   $safehole->wrap(\&Apache::outputtags::multipart,$safeeval,'&multipart');
  703:   $safehole->wrap(\&Apache::lonnet::EXT,$safeeval,'&EXT');
  704:   $safehole->wrap(\&Apache::chemresponse::chem_standard_order,$safeeval,
  705: 		  '&chem_standard_order');
  706:   $safehole->wrap(\&Apache::response::check_status,$safeeval,'&check_status');
  707: 
  708:   $safehole->wrap(\&Math::Cephes::asin,$safeeval,'&asin');
  709:   $safehole->wrap(\&Math::Cephes::acos,$safeeval,'&acos');
  710:   $safehole->wrap(\&Math::Cephes::atan,$safeeval,'&atan');
  711:   $safehole->wrap(\&Math::Cephes::sinh,$safeeval,'&sinh');
  712:   $safehole->wrap(\&Math::Cephes::cosh,$safeeval,'&cosh');
  713:   $safehole->wrap(\&Math::Cephes::tanh,$safeeval,'&tanh');
  714:   $safehole->wrap(\&Math::Cephes::asinh,$safeeval,'&asinh');
  715:   $safehole->wrap(\&Math::Cephes::acosh,$safeeval,'&acosh');
  716:   $safehole->wrap(\&Math::Cephes::atanh,$safeeval,'&atanh');
  717:   $safehole->wrap(\&Math::Cephes::erf,$safeeval,'&erf');
  718:   $safehole->wrap(\&Math::Cephes::erfc,$safeeval,'&erfc');
  719:   $safehole->wrap(\&Math::Cephes::j0,$safeeval,'&j0');
  720:   $safehole->wrap(\&Math::Cephes::j1,$safeeval,'&j1');
  721:   $safehole->wrap(\&Math::Cephes::jn,$safeeval,'&jn');
  722:   $safehole->wrap(\&Math::Cephes::jv,$safeeval,'&jv');
  723:   $safehole->wrap(\&Math::Cephes::y0,$safeeval,'&y0');
  724:   $safehole->wrap(\&Math::Cephes::y1,$safeeval,'&y1');
  725:   $safehole->wrap(\&Math::Cephes::yn,$safeeval,'&yn');
  726:   $safehole->wrap(\&Math::Cephes::yv,$safeeval,'&yv');
  727:   
  728:   $safehole->wrap(\&Math::Cephes::bdtr  ,$safeeval,'&bdtr'  );
  729:   $safehole->wrap(\&Math::Cephes::bdtrc ,$safeeval,'&bdtrc' );
  730:   $safehole->wrap(\&Math::Cephes::bdtri ,$safeeval,'&bdtri' );
  731:   $safehole->wrap(\&Math::Cephes::btdtr ,$safeeval,'&btdtr' );
  732:   $safehole->wrap(\&Math::Cephes::chdtr ,$safeeval,'&chdtr' );
  733:   $safehole->wrap(\&Math::Cephes::chdtrc,$safeeval,'&chdtrc');
  734:   $safehole->wrap(\&Math::Cephes::chdtri,$safeeval,'&chdtri');
  735:   $safehole->wrap(\&Math::Cephes::fdtr  ,$safeeval,'&fdtr'  );
  736:   $safehole->wrap(\&Math::Cephes::fdtrc ,$safeeval,'&fdtrc' );
  737:   $safehole->wrap(\&Math::Cephes::fdtri ,$safeeval,'&fdtri' );
  738:   $safehole->wrap(\&Math::Cephes::gdtr  ,$safeeval,'&gdtr'  );
  739:   $safehole->wrap(\&Math::Cephes::gdtrc ,$safeeval,'&gdtrc' );
  740:   $safehole->wrap(\&Math::Cephes::nbdtr ,$safeeval,'&nbdtr' );
  741:   $safehole->wrap(\&Math::Cephes::nbdtrc,$safeeval,'&nbdtrc');
  742:   $safehole->wrap(\&Math::Cephes::nbdtri,$safeeval,'&nbdtri');
  743:   $safehole->wrap(\&Math::Cephes::ndtr  ,$safeeval,'&ndtr'  );
  744:   $safehole->wrap(\&Math::Cephes::ndtri ,$safeeval,'&ndtri' );
  745:   $safehole->wrap(\&Math::Cephes::pdtr  ,$safeeval,'&pdtr'  );
  746:   $safehole->wrap(\&Math::Cephes::pdtrc ,$safeeval,'&pdtrc' );
  747:   $safehole->wrap(\&Math::Cephes::pdtri ,$safeeval,'&pdtri' );
  748:   $safehole->wrap(\&Math::Cephes::stdtr ,$safeeval,'&stdtr' );
  749:   $safehole->wrap(\&Math::Cephes::stdtri,$safeeval,'&stdtri');
  750: 
  751: #  $safehole->wrap(\&Math::Cephes::new_fract,$safeeval,'&new_fract');
  752: #  $safehole->wrap(\&Math::Cephes::radd,$safeeval,'&radd');
  753: #  $safehole->wrap(\&Math::Cephes::rsub,$safeeval,'&rsub');
  754: #  $safehole->wrap(\&Math::Cephes::rmul,$safeeval,'&rmul');
  755: #  $safehole->wrap(\&Math::Cephes::rdiv,$safeeval,'&rdiv');
  756: #  $safehole->wrap(\&Math::Cephes::euclid,$safeeval,'&euclid');
  757: 
  758:   $safehole->wrap(\&Math::Random::random_beta,$safeeval,'&math_random_beta');
  759:   $safehole->wrap(\&Math::Random::random_chi_square,$safeeval,'&math_random_chi_square');
  760:   $safehole->wrap(\&Math::Random::random_exponential,$safeeval,'&math_random_exponential');
  761:   $safehole->wrap(\&Math::Random::random_f,$safeeval,'&math_random_f');
  762:   $safehole->wrap(\&Math::Random::random_gamma,$safeeval,'&math_random_gamma');
  763:   $safehole->wrap(\&Math::Random::random_multivariate_normal,$safeeval,'&math_random_multivariate_normal');
  764:   $safehole->wrap(\&Math::Random::random_multinomial,$safeeval,'&math_random_multinomial');
  765:   $safehole->wrap(\&Math::Random::random_noncentral_chi_square,$safeeval,'&math_random_noncentral_chi_square');
  766:   $safehole->wrap(\&Math::Random::random_noncentral_f,$safeeval,'&math_random_noncentral_f');
  767:   $safehole->wrap(\&Math::Random::random_normal,$safeeval,'&math_random_normal');
  768:   $safehole->wrap(\&Math::Random::random_permutation,$safeeval,'&math_random_permutation');
  769:   $safehole->wrap(\&Math::Random::random_permuted_index,$safeeval,'&math_random_permuted_index');
  770:   $safehole->wrap(\&Math::Random::random_uniform,$safeeval,'&math_random_uniform');
  771:   $safehole->wrap(\&Math::Random::random_poisson,$safeeval,'&math_random_poisson');
  772:   $safehole->wrap(\&Math::Random::random_uniform_integer,$safeeval,'&math_random_uniform_integer');
  773:   $safehole->wrap(\&Math::Random::random_negative_binomial,$safeeval,'&math_random_negative_binomial');
  774:   $safehole->wrap(\&Math::Random::random_binomial,$safeeval,'&math_random_binomial');
  775:   $safehole->wrap(\&Math::Random::random_seed_from_phrase,$safeeval,'&random_seed_from_phrase');
  776:   $safehole->wrap(\&Math::Random::random_set_seed_from_phrase,$safeeval,'&random_set_seed_from_phrase');
  777:   $safehole->wrap(\&Math::Random::random_get_seed,$safeeval,'&random_get_seed');
  778:   $safehole->wrap(\&Math::Random::random_set_seed,$safeeval,'&random_set_seed');
  779:   $safehole->wrap(\&Apache::lonxml::error,$safeeval,'&LONCAPA_INTERNAL_ERROR');
  780:   $safehole->wrap(\&Apache::lonxml::debug,$safeeval,'&LONCAPA_INTERNAL_DEBUG');
  781:   $safehole->wrap(\&Apache::caparesponse::get_sigrange,$safeeval,'&LONCAPA_INTERNAL_get_sigrange');
  782: 
  783: #need to inspect this class of ops
  784: # $safeeval->deny(":base_orig");
  785:   $safeeval->permit("require");
  786:   $safeinit .= ';$external::target="'.$target.'";';
  787:   my $rndseed;
  788:   my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
  789:   $rndseed=&Apache::lonnet::rndseed($symb,$courseid,$domain,$name);
  790:   $safeinit .= ';$external::randomseed="'.$rndseed.'";';
  791:   &Apache::lonxml::debug("Setting rndseed to $rndseed");
  792:   &Apache::run::run($safeinit,$safeeval);
  793: 
  794: }
  795: 
  796: sub default_homework_load {
  797:     my ($safeeval)=@_;
  798:     &Apache::lonxml::debug('Loading default_homework');
  799:     my $default=&Apache::lonnet::getfile('/home/httpd/html/res/adm/includes/default_homework.lcpm');
  800:     if ($default eq -1) {
  801: 	&Apache::lonxml::error("<b>Unable to find <i>default_homework.lcpm</i></b>");
  802:     } else {
  803: 	&Apache::run::run($default,$safeeval);
  804: 	$Apache::lonxml::default_homework_loaded=1;
  805:     }
  806: }
  807: 
  808: {
  809:     my $alarm_depth;
  810:     sub init_alarm {
  811: 	alarm(0);
  812: 	$alarm_depth=0;
  813:     }
  814: 
  815:     sub start_alarm {
  816: 	if ($alarm_depth<1) {
  817: 	    my $old=alarm($Apache::lonnet::perlvar{'lonScriptTimeout'});
  818: 	    if ($old) {
  819: 		&Apache::lonxml::error("Cancelled an alarm of $old, this shouldn't occur.");
  820: 	    }
  821: 	}
  822: 	$alarm_depth++;
  823:     }
  824: 
  825:     sub end_alarm {
  826: 	$alarm_depth--;
  827: 	if ($alarm_depth<1) { alarm(0); }
  828:     }
  829: }
  830: my $metamode_was;
  831: sub startredirection {
  832:     if (!$Apache::lonxml::redirection) {
  833: 	$metamode_was=$Apache::lonxml::metamode;
  834:     }
  835:     $Apache::lonxml::metamode=0;
  836:     $Apache::lonxml::redirection++;
  837:     push (@Apache::lonxml::outputstack, '');
  838: }
  839: 
  840: sub endredirection {
  841:     if (!$Apache::lonxml::redirection) {
  842: 	&Apache::lonxml::error("Endredirection was called, before a startredirection, perhaps you have unbalanced tags. Some debuging information:".join ":",caller);
  843: 	return '';
  844:     }
  845:     $Apache::lonxml::redirection--;
  846:     if (!$Apache::lonxml::redirection) {
  847: 	$Apache::lonxml::metamode=$metamode_was;
  848:     }
  849:     pop @Apache::lonxml::outputstack;
  850: }
  851: 
  852: sub end_tag {
  853:   my ($tagstack,$parstack,$token)=@_;
  854:   pop(@$tagstack);
  855:   pop(@$parstack);
  856:   &decreasedepth($token);
  857: }
  858: 
  859: sub initdepth {
  860:   @Apache::lonxml::depthcounter=();
  861:   $Apache::lonxml::depth=-1;
  862:   $Apache::lonxml::olddepth=-1;
  863: }
  864: 
  865: my @timers;
  866: my $lasttime;
  867: sub increasedepth {
  868:   my ($token) = @_;
  869:   $Apache::lonxml::depth++;
  870:   $Apache::lonxml::depthcounter[$Apache::lonxml::depth]++;
  871:   if ($Apache::lonxml::depthcounter[$Apache::lonxml::depth]==1) {
  872:     $Apache::lonxml::olddepth=$Apache::lonxml::depth;
  873:   }
  874:   my $time;
  875:   if ($Apache::lonxml::debug eq "1") {
  876:       push(@timers,[&gettimeofday()]);
  877:       $time=&tv_interval($lasttime);
  878:       $lasttime=[&gettimeofday()];
  879:   }
  880:   my $spacing='  'x($Apache::lonxml::depth-1);
  881:   my $curdepth=join('_',@Apache::lonxml::depthcounter);
  882:   &Apache::lonxml::debug("s$spacing$Apache::lonxml::depth : $Apache::lonxml::olddepth : $curdepth : $token->[1] : $time : \n");
  883: #print "<br />s $Apache::lonxml::depth : $Apache::lonxml::olddepth : $curdepth : $token->[1]\n";
  884: }
  885: 
  886: sub decreasedepth {
  887:   my ($token) = @_;
  888:   $Apache::lonxml::depth--;
  889:   if ($Apache::lonxml::depth<$Apache::lonxml::olddepth-1) {
  890:     $#Apache::lonxml::depthcounter--;
  891:     $Apache::lonxml::olddepth=$Apache::lonxml::depth+1;
  892:   }
  893:   if (  $Apache::lonxml::depth < -1) {
  894:     &Apache::lonxml::warning(&mt("Missing tags, unable to properly run file."));
  895:     $Apache::lonxml::depth='-1';
  896:   }
  897:   my ($timer,$time);
  898:   if ($Apache::lonxml::debug eq "1") {
  899:       $timer=pop(@timers);
  900:       $time=&tv_interval($lasttime);
  901:       $lasttime=[&gettimeofday()];
  902:   }
  903:   my $spacing='  'x$Apache::lonxml::depth;
  904:   my $curdepth=join('_',@Apache::lonxml::depthcounter);
  905:   &Apache::lonxml::debug("e$spacing$Apache::lonxml::depth : $Apache::lonxml::olddepth : $curdepth : $token->[1] : $time : ".&tv_interval($timer)."\n");
  906: #print "<br />e $Apache::lonxml::depth : $Apache::lonxml::olddepth : $token->[1] : $curdepth\n";
  907: }
  908: 
  909: sub get_all_text_unbalanced {
  910: #there is a copy of this in lonpublisher.pm
  911:     my($tag,$pars)= @_;
  912:     my $token;
  913:     my $result='';
  914:     $tag='<'.$tag.'>';
  915:     while ($token = $$pars[-1]->get_token) {
  916: 	if (($token->[0] eq 'T')||($token->[0] eq 'C')||($token->[0] eq 'D')) {
  917: 	    $result.=$token->[1];
  918: 	} elsif ($token->[0] eq 'PI') {
  919: 	    $result.=$token->[2];
  920: 	} elsif ($token->[0] eq 'S') {
  921: 	    $result.=$token->[4];
  922: 	} elsif ($token->[0] eq 'E')  {
  923: 	    $result.=$token->[2];
  924: 	}
  925: 	if ($result =~ /\Q$tag\E/is) {
  926: 	    ($result,my $redo)=$result =~ /(.*)\Q$tag\E(.*)/is;
  927: 	    #&Apache::lonxml::debug('Got a winner with leftovers ::'.$2);
  928: 	    #&Apache::lonxml::debug('Result is :'.$1);
  929: 	    $redo=$tag.$redo;
  930: 	    &Apache::lonxml::newparser($pars,\$redo);
  931: 	    last;
  932: 	}
  933:     }
  934:     return $result
  935: }
  936: 
  937: sub increment_counter {
  938:     my ($increment) = @_;
  939:     if (defined($increment) && $increment gt 0) {
  940: 	$Apache::lonxml::counter+=$increment;
  941:     } else {
  942: 	$Apache::lonxml::counter++;
  943:     }
  944:     $Apache::lonxml::counter_changed=1;
  945: }
  946: 
  947: sub init_counter {
  948:     if (defined($env{'form.counter'})) {
  949: 	$Apache::lonxml::counter=$env{'form.counter'};
  950: 	$Apache::lonxml::counter_changed=0;
  951:     } else {
  952: 	$Apache::lonxml::counter=1;
  953: 	$Apache::lonxml::counter_changed=1;
  954:     }
  955: }
  956: 
  957: sub store_counter {
  958:     &Apache::lonnet::appenv(('form.counter' => $Apache::lonxml::counter));
  959:     return '';
  960: }
  961: 
  962: sub get_all_text {
  963:     my($tag,$pars,$style)= @_;
  964:     my $gotfullstack=1;
  965:     if (ref($pars) ne 'ARRAY') {
  966: 	$gotfullstack=0;
  967: 	$pars=[$pars];
  968:     }
  969:     if (ref($style) ne 'HASH') {
  970: 	$style={};
  971:     }
  972:     my $depth=0;
  973:     my $token;
  974:     my $result='';
  975:     if ( $tag =~ m:^/: ) { 
  976: 	my $tag=substr($tag,1); 
  977: 	#&Apache::lonxml::debug("have:$tag:");
  978: 	my $top_empty=0;
  979: 	while (($depth >=0) && ($#$pars > -1) && (!$top_empty)) {
  980: 	    while (($depth >=0) && ($token = $$pars[-1]->get_token)) {
  981: 		#&Apache::lonxml::debug("e token:$token->[0]:$depth:$token->[1]:".$#$pars.":".$#Apache::lonxml::pwd);
  982: 		if (($token->[0] eq 'T')||($token->[0] eq 'C')||($token->[0] eq 'D')) {
  983: 		    $result.=$token->[1];
  984: 		} elsif ($token->[0] eq 'PI') {
  985: 		    $result.=$token->[2];
  986: 		} elsif ($token->[0] eq 'S') {
  987: 		    if ($token->[1] =~ /^\Q$tag\E$/i) { $depth++; }
  988: 		    if ($token->[1] =~ /^LONCAPA_INTERNAL_TURN_STYLE_ON$/) { $Apache::lonxml::usestyle=1; }
  989: 		    if ($token->[1] =~ /^LONCAPA_INTERNAL_TURN_STYLE_OFF$/) { $Apache::lonxml::usestyle=0; }
  990: 		    $result.=$token->[4];
  991: 		} elsif ($token->[0] eq 'E')  {
  992: 		    if ( $token->[1] =~ /^\Q$tag\E$/i) { $depth--; }
  993: 		    #skip sending back the last end tag
  994: 		    if ($depth == 0 && exists($$style{'/'.$token->[1]}) && $Apache::lonxml::usestyle) {
  995: 			my $string=
  996: 			    '<LONCAPA_INTERNAL_TURN_STYLE_OFF end="yes" />'.
  997: 				$$style{'/'.$token->[1]}.
  998: 				    $token->[2].
  999: 					'<LONCAPA_INTERNAL_TURN_STYLE_ON />';
 1000: 			&Apache::lonxml::newparser($pars,\$string);
 1001: 			#&Apache::lonxml::debug("reParsing $string");
 1002: 			next;
 1003: 		    }
 1004: 		    if ($depth > -1) {
 1005: 			$result.=$token->[2];
 1006: 		    } else {
 1007: 			$$pars[-1]->unget_token($token);
 1008: 		    }
 1009: 		}
 1010: 	    }
 1011: 	    if (($depth >=0) && ($#$pars == 0) ) { $top_empty=1; }
 1012: 	    if (($depth >=0) && ($#$pars > 0) ) {
 1013: 		pop(@$pars);
 1014: 		pop(@Apache::lonxml::pwd);
 1015: 	    }
 1016: 	}
 1017: 	if ($top_empty && $depth >= 0) {
 1018: 	    #never found the end tag ran out of text, throw error send back blank
 1019: 	    &error('Never found end tag for &lt;'.$tag.
 1020: 		   '&gt; current string <pre>'.
 1021: 		   &HTML::Entities::encode($result,'<>&"').
 1022: 		   '</pre>');
 1023: 	    if ($gotfullstack) {
 1024: 		my $newstring='</'.$tag.'>'.$result;
 1025: 		&Apache::lonxml::newparser($pars,\$newstring);
 1026: 	    }
 1027: 	    $result='';
 1028: 	}
 1029:     } else {
 1030: 	while ($#$pars > -1) {
 1031: 	    while ($token = $$pars[-1]->get_token) {
 1032: 		#&Apache::lonxml::debug("s token:$token->[0]:$depth:$token->[1]");
 1033: 		if (($token->[0] eq 'T')||($token->[0] eq 'C')||
 1034: 		    ($token->[0] eq 'D')) {
 1035: 		    $result.=$token->[1];
 1036: 		} elsif ($token->[0] eq 'PI') {
 1037: 		    $result.=$token->[2];
 1038: 		} elsif ($token->[0] eq 'S') {
 1039: 		    if ( $token->[1] =~ /^\Q$tag\E$/i) {
 1040: 			$$pars[-1]->unget_token($token); last;
 1041: 		    } else {
 1042: 			$result.=$token->[4];
 1043: 		    }
 1044: 		    if ($token->[1] =~ /^LONCAPA_INTERNAL_TURN_STYLE_ON$/) { $Apache::lonxml::usestyle=1; }
 1045: 		    if ($token->[1] =~ /^LONCAPA_INTERNAL_TURN_STYLE_OFF$/) { $Apache::lonxml::usestyle=0; }
 1046: 		} elsif ($token->[0] eq 'E')  {
 1047: 		    $result.=$token->[2];
 1048: 		}
 1049: 	    }
 1050: 	    if (($#$pars > 0) ) {
 1051: 		pop(@$pars);
 1052: 		pop(@Apache::lonxml::pwd);
 1053: 	    } else { last; }
 1054: 	}
 1055:     }
 1056:     #&Apache::lonxml::debug("Exit:$result:");
 1057:     return $result
 1058: }
 1059: 
 1060: sub newparser {
 1061:   my ($parser,$contentref,$dir) = @_;
 1062:   push (@$parser,HTML::LCParser->new($contentref));
 1063:   $$parser[-1]->xml_mode(1);
 1064:   $$parser[-1]->marked_sections(1);
 1065:   if ( $dir eq '' ) {
 1066:     push (@Apache::lonxml::pwd, $Apache::lonxml::pwd[$#Apache::lonxml::pwd]);
 1067:   } else {
 1068:     push (@Apache::lonxml::pwd, $dir);
 1069:   } 
 1070: }
 1071: 
 1072: sub parstring {
 1073:   my ($token) = @_;
 1074:   my $temp='';
 1075:   foreach (@{$token->[3]}) {
 1076:     unless ($_=~/\W/) {
 1077:       my $val=$token->[2]->{$_};
 1078:       $val =~ s/([\%\@\\\"\'])/\\$1/g;
 1079:       $val =~ s/(\$[^{a-zA-Z_])/\\$1/g;
 1080:       $val =~ s/(\$)$/\\$1/;
 1081:       #if ($val =~ m/^[\%\@]/) { $val="\\".$val; }
 1082:       $temp .= "my \$$_=\"$val\";";
 1083:     }
 1084:   }
 1085:   return $temp;
 1086: }
 1087: 
 1088: sub writeallows {
 1089:     unless ($#extlinks>=0) { return; }
 1090:     my $thisurl='/res/'.&Apache::lonnet::declutter(shift);
 1091:     if ($env{'httpref.'.$thisurl}) {
 1092: 	$thisurl=$env{'httpref.'.$thisurl};
 1093:     }
 1094:     my $thisdir=$thisurl;
 1095:     $thisdir=~s/\/[^\/]+$//;
 1096:     my %httpref=();
 1097:     foreach (@extlinks) {
 1098:        $httpref{'httpref.'.
 1099:  	        &Apache::lonnet::hreflocation($thisdir,$_)}=$thisurl;
 1100:     }
 1101:     @extlinks=();
 1102:     &Apache::lonnet::appenv(%httpref);
 1103: }
 1104: 
 1105: sub register_ssi {
 1106:     my ($url,%form)=@_;
 1107:     push (@Apache::lonxml::ssi_info,{'url'=>$url,'form'=>\%form});
 1108:     return '';
 1109: }
 1110: 
 1111: sub do_registered_ssi {
 1112:     foreach my $info (@Apache::lonxml::ssi_info) {
 1113: 	my %form=%{ $info->{'form'}};
 1114: 	my $url=$info->{'url'};
 1115: 	&Apache::lonnet::ssi($url,%form);
 1116:     }
 1117: }
 1118: #
 1119: # Afterburner handles anchors, highlights and links
 1120: #
 1121: sub afterburn {
 1122:     my $result=shift;
 1123:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 1124: 					    ['highlight','anchor','link']);
 1125:     if ($env{'form.highlight'}) {
 1126:        foreach (split(/\,/,$env{'form.highlight'})) {
 1127:            my $anchorname=$_;
 1128: 	   my $matchthis=$anchorname;
 1129:            $matchthis=~s/\_+/\\s\+/g;
 1130:            $result=~s/(\Q$matchthis\E)/\<font color=\"red\"\>$1\<\/font\>/gs;
 1131:        }
 1132:     }
 1133:     if ($env{'form.link'}) {
 1134:        foreach (split(/\,/,$env{'form.link'})) {
 1135:            my ($anchorname,$linkurl)=split(/\>/,$_);
 1136: 	   my $matchthis=$anchorname;
 1137:            $matchthis=~s/\_+/\\s\+/g;
 1138:            $result=~s/(\Q$matchthis\E)/\<a href=\"$linkurl\"\>$1\<\/a\>/gs;
 1139:        }
 1140:     }
 1141:     if ($env{'form.anchor'}) {
 1142:         my $anchorname=$env{'form.anchor'};
 1143: 	my $matchthis=$anchorname;
 1144:         $matchthis=~s/\_+/\\s\+/g;
 1145:         $result=~s/(\Q$matchthis\E)/\<a name=\"$anchorname\"\>$1\<\/a\>/s;
 1146:         $result.=(<<"ENDSCRIPT");
 1147: <script type="text/javascript">
 1148:     document.location.hash='$anchorname';
 1149: </script>
 1150: ENDSCRIPT
 1151:     }
 1152:     return $result;
 1153: }
 1154: 
 1155: sub storefile {
 1156:     my ($file,$contents)=@_;
 1157:     &Apache::lonnet::correct_line_ends(\$contents);
 1158:     if (my $fh=Apache::File->new('>'.$file)) {
 1159: 	print $fh $contents;
 1160:         $fh->close();
 1161:         return 1;
 1162:     } else {
 1163: 	&warning("Unable to save file $file");
 1164: 	return 0;
 1165:     }
 1166: }
 1167: 
 1168: sub createnewhtml {
 1169:     my $title=&mt('Title of document goes here');
 1170:     my $body=&mt('Body of document goes here');
 1171:     my $filecontents=(<<SIMPLECONTENT);
 1172: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml/11/DTD/xhtml11.dtd">
 1173: <html>
 1174: <head>
 1175: <title>$title</title>
 1176: </head>
 1177: <body bgcolor="#FFFFFF">
 1178: $body
 1179: </body>
 1180: </html>
 1181: SIMPLECONTENT
 1182:     return $filecontents;
 1183: }
 1184: 
 1185: sub createnewsty {
 1186:   my $filecontents=(<<SIMPLECONTENT);
 1187: <definetag name="">
 1188:     <render>
 1189:        <web></web>
 1190:        <tex></tex>
 1191:     </render>
 1192: </definetag>
 1193: SIMPLECONTENT
 1194:   return $filecontents;
 1195: }
 1196: 
 1197: 
 1198: sub inserteditinfo {
 1199:       my ($result,$filecontents,$filetype)=@_;
 1200:       $filecontents = &HTML::Entities::encode($filecontents,'<>&"');
 1201: #      my $editheader='<a href="#editsection">Edit below</a><hr />';
 1202:       my $xml_help = '';
 1203:       my $initialize='';
 1204:       if ($filetype eq 'html') {
 1205: 	  my $addbuttons=&Apache::lonhtmlcommon::htmlareaaddbuttons();
 1206: 	  $initialize=&Apache::lonhtmlcommon::htmlareaheaders().
 1207: 	      &Apache::lonhtmlcommon::spellheader();
 1208: 	  if (!&Apache::lonhtmlcommon::htmlareablocked() &&
 1209: 	      &Apache::lonhtmlcommon::htmlareabrowser()) {
 1210: 	      $initialize.=(<<FULLPAGE);
 1211: <script type="text/javascript">
 1212: $addbuttons
 1213: 
 1214:     HTMLArea.loadPlugin("FullPage");
 1215: 
 1216:     function initDocument() {
 1217: 	var editor=new HTMLArea("filecont",config);
 1218: 	editor.registerPlugin(FullPage);
 1219: 	editor.generate();
 1220:     }
 1221: </script>
 1222: FULLPAGE
 1223:           } else {
 1224: 	      $initialize.=(<<FULLPAGE);
 1225: <script type="text/javascript">
 1226: $addbuttons
 1227:     function initDocument() {
 1228:     }
 1229: </script>
 1230: FULLPAGE
 1231: 	  }
 1232:           $result=~s/\<body([^\>]*)\>/\<body onload="initDocument()" $1\>/i;
 1233: 	  $xml_help=&Apache::loncommon::helpLatexCheatsheet();
 1234:       }
 1235:       my $cleanbut = '';
 1236:       if ($filetype eq 'html') {
 1237: 	  $cleanbut='<input type="submit" name="attemptclean" value="'.
 1238: 	      &mt('Save and then attempt to clean HTML').'" />';
 1239:       }
 1240:       my $titledisplay=&display_title();
 1241:       my %lt=&Apache::lonlocal::texthash('st' => 'Save this',
 1242: 					 'vi' => 'View',
 1243: 					 'ed' => 'Edit');
 1244:       my $buttons=(<<BUTTONS);
 1245: $cleanbut
 1246: <input type="submit" name="savethisfile" accesskey="s"  value="$lt{'st'}" />
 1247: <input type="submit" name="viewmode" accesskey="v" value="$lt{'vi'}" />
 1248: BUTTONS
 1249:       $buttons.=&Apache::lonhtmlcommon::spelllink('xmledit','filecont');
 1250:       $buttons.=&Apache::lonhtmlcommon::htmlareaselectactive('filecont');
 1251:       my $editfooter=(<<ENDFOOTER);
 1252: $initialize
 1253: <hr />
 1254: <a name="editsection" />
 1255: <form method="post" name="xmledit">
 1256: $xml_help
 1257: <input type="hidden" name="editmode" value="$lt{'ed'}" />
 1258: $buttons<br />
 1259: <textarea style="width:100%" cols="80" rows="44" name="filecont" id="filecont">$filecontents</textarea>
 1260: <br />$buttons
 1261: <br />
 1262: </form>
 1263: $titledisplay
 1264: </body>
 1265: ENDFOOTER
 1266: #      $result=~s/(\<body[^\>]*\>)/$1$editheader/is;
 1267:       $result=~s/(\<\/body\>)/$editfooter/is;
 1268:       return $result;
 1269: }
 1270: 
 1271: sub get_target {
 1272:   my $viewgrades=&Apache::lonnet::allowed('vgr',$env{'request.course.id'});
 1273:   if ( $env{'request.state'} eq 'published') {
 1274:     if ( defined($env{'form.grade_target'})
 1275: 	 && ($viewgrades == 'F' )) {
 1276:       return ($env{'form.grade_target'});
 1277:     } elsif (defined($env{'form.grade_target'})) {
 1278:       if (($env{'form.grade_target'} eq 'web') ||
 1279: 	  ($env{'form.grade_target'} eq 'tex') ) {
 1280: 	return $env{'form.grade_target'}
 1281:       } else {
 1282: 	return 'web';
 1283:       }
 1284:     } else {
 1285:       return 'web';
 1286:     }
 1287:   } elsif ($env{'request.state'} eq 'construct') {
 1288:     if ( defined($env{'form.grade_target'})) {
 1289:       return ($env{'form.grade_target'});
 1290:     } else {
 1291:       return 'web';
 1292:     }
 1293:   } else {
 1294:     return 'web';
 1295:   }
 1296: }
 1297: 
 1298: sub handler {
 1299:     my $request=shift;
 1300:     
 1301:     my $target=&get_target();
 1302:     
 1303:     $Apache::lonxml::debug=$env{'user.debug'};
 1304:     
 1305:     &Apache::loncommon::content_type($request,'text/html');
 1306:     &Apache::loncommon::no_cache($request);
 1307:     if ($env{'request.state'} eq 'published') {
 1308: 	$request->set_last_modified(&Apache::lonnet::metadata($request->uri,
 1309: 							      'lastrevisiondate'));
 1310:     }
 1311:     $request->send_http_header;
 1312:     
 1313:     return OK if $request->header_only;
 1314: 
 1315: 
 1316:     my $file=&Apache::lonnet::filelocation("",$request->uri);
 1317:     my $filetype;
 1318:     if ($file =~ /\.sty$/) {
 1319: 	$filetype='sty';
 1320:     } else {
 1321: 	$filetype='html';
 1322:     }
 1323: #
 1324: # Edit action? Save file.
 1325: #
 1326:     unless ($env{'request.state'} eq 'published') {
 1327: 	if (($env{'form.savethisfile'}) || ($env{'form.attemptclean'})) {
 1328: 	    if (&storefile($file,$env{'form.filecont'})) {
 1329: 		&Apache::lonxml::info("<font COLOR=\"#0000FF\">".
 1330: 				      &mt('Updated').": ".
 1331: 				      &Apache::lonlocal::locallocaltime(time).
 1332: 				      " </font>");
 1333: 	    } 
 1334: 	}
 1335:     }
 1336:     my %mystyle;
 1337:     my $result = '';
 1338:     my $filecontents=&Apache::lonnet::getfile($file);
 1339:     if ($filecontents eq -1) {
 1340: 	my $bodytag=&Apache::loncommon::bodytag('File Error');
 1341: 	my $fnf=&mt('File not found');
 1342: 	$result=(<<ENDNOTFOUND);
 1343: <html>
 1344: <head>
 1345: <title>$fnf</title>
 1346: </head>
 1347: $bodytag
 1348: <b>$fnf: $file</b>
 1349: </body>
 1350: </html>
 1351: ENDNOTFOUND
 1352:         $filecontents='';
 1353: 	if ($env{'request.state'} ne 'published') {
 1354: 	    if ($filetype eq 'sty') {
 1355: 		$filecontents=&createnewsty();
 1356: 	    } else {
 1357: 		$filecontents=&createnewhtml();
 1358: 	    }
 1359: 	    $env{'form.editmode'}='Edit'; #force edit mode
 1360: 	}
 1361:     } else {
 1362: 	unless ($env{'request.state'} eq 'published') {
 1363: 	    if ($filecontents=~/BEGIN LON-CAPA Internal/) {
 1364: 		&Apache::lonxml::error(&mt('This file appears to be a rendering of a Lon-CAPA resource. If this is correct, this resource will act very oddly and incorrectly.'));
 1365: 	    }
 1366: 
 1367: 	    if ($env{'form.attemptclean'}) {
 1368: 		$filecontents=&htmlclean($filecontents,1);
 1369: 	    }
 1370: #
 1371: # we are in construction space, see if edit mode forced
 1372:             &Apache::loncommon::get_unprocessed_cgi
 1373:                           ($ENV{'QUERY_STRING'},['editmode']);
 1374: 	}
 1375: 	if (!$env{'form.editmode'} || $env{'form.viewmode'}) {
 1376: 	    $result = &Apache::lonxml::xmlparse($request,$target,$filecontents,
 1377: 						'',%mystyle);
 1378: 	    undef($Apache::lonhomework::parsing_a_task);
 1379: 	}
 1380:     }
 1381:     
 1382: #
 1383: # Edit action? Insert editing commands
 1384: #
 1385:     unless ($env{'request.state'} eq 'published') {
 1386: 	if ($env{'form.editmode'} && (!($env{'form.viewmode'}))) {
 1387: 	    my $displayfile=$request->uri;
 1388: 	    $displayfile=~s/^\/[^\/]*//;
 1389: 	    my $bodytag='<body bgcolor="#FFFFFF">';
 1390: 	    if ($env{'environment.remote'} eq 'off') {
 1391: 		$bodytag=&Apache::loncommon::bodytag();
 1392: 	    }
 1393: 	    $result='<html>'.$bodytag.
 1394: 		&Apache::lonxml::message_location().'<h3>'.
 1395: 		$displayfile.
 1396: 		'</h3></body></html>';
 1397: 	    $result=&inserteditinfo($result,$filecontents,$filetype);
 1398: 	}
 1399:     }
 1400:     if ($filetype eq 'html') { writeallows($request->uri); }
 1401: 	
 1402:     
 1403:     &Apache::lonxml::add_messages(\$result);
 1404:     $request->print($result);
 1405:     
 1406:     return OK;
 1407: }
 1408: 
 1409: sub display_title {
 1410:     my $result;
 1411:     if ($env{'request.state'} eq 'construct') {
 1412: 	my $title=&Apache::lonnet::gettitle();
 1413: 	if (!defined($title) || $title eq '') {
 1414: 	    $title = $env{'request.filename'};
 1415: 	    $title = substr($title, rindex($title, '/') + 1);
 1416: 	}
 1417: 	$result = "<script type='text/javascript'>top.document.title = '$title - LON-CAPA Construction Space';</script>";
 1418:     }
 1419:     return $result;
 1420: }
 1421: 
 1422: sub debug {
 1423:     if ($Apache::lonxml::debug eq "1") {
 1424: 	$|=1;
 1425: 	my $request=$Apache::lonxml::request;
 1426: 	if (!$request) { $request=Apache->request; }
 1427: 	$request->print('<font size="-2"><pre>DEBUG:'.&HTML::Entities::encode($_[0],'<>&"')."</pre></font>\n");
 1428: 	#&Apache::lonnet::logthis($_[0]);
 1429:     }
 1430: }
 1431: 
 1432: sub show_error_warn_msg {
 1433:     if ($env{'request.filename'} eq '/home/httpd/html/res/lib/templates/simpleproblem.problem' &&
 1434: 	&Apache::lonnet::allowed('mdc',$env{'request.course.id'})) {
 1435: 	return 1;
 1436:     }
 1437:     return (($Apache::lonxml::debug eq 1) ||
 1438: 	    ($env{'request.state'} eq 'construct') ||
 1439: 	    ($Apache::lonhomework::browse eq 'F'
 1440: 	     &&
 1441: 	     $env{'form.show_errors'} eq 'on'));
 1442: }
 1443: 
 1444: sub error {
 1445:     $errorcount++;
 1446:     if ( &show_error_warn_msg() ) {
 1447: 	# If printing in construction space, put the error inside <pre></pre>
 1448: 	push(@Apache::lonxml::error_messages,
 1449: 	     $Apache::lonxml::warnings_error_header.
 1450: 	     "<b>ERROR:</b>".join("<br />\n",@_)."<br />\n");
 1451: 	$Apache::lonxml::warnings_error_header='';
 1452:     } else {
 1453: 	my $errormsg;
 1454: 	my ($symb)=&Apache::lonnet::symbread();
 1455: 	if ( !$symb ) {
 1456: 	    #public or browsers
 1457: 	    $errormsg=&mt("An error occured while processing this resource. The author has been notified.");
 1458: 	} 
 1459: 	#notify author
 1460: 	&Apache::lonmsg::author_res_msg($env{'request.filename'},join('<br />',@_));
 1461: 	#notify course
 1462: 	if ( $symb && $env{'request.course.id'} ) {
 1463: 	    my (undef,%users)=&Apache::lonfeedback::decide_receiver(undef,0,1,1,1);
 1464: 	    my $declutter=&Apache::lonnet::declutter($env{'request.filename'});
 1465: 	    my @userlist;
 1466: 	    foreach (keys %users) {
 1467: 		my ($user,$domain) = split(/:/, $_);
 1468: 		push(@userlist,"$user\@$domain");
 1469: 		&Apache::lonmsg::user_normal_msg($user,$domain,
 1470: 						 "Error [$declutter]",join('<br />',@_));
 1471: 	    }
 1472: 	    if ($env{'request.role.adv'}) {
 1473: 		$errormsg=&mt("An error occured while processing this resource. The course personnel ([_1]) and the author have been notified.",join(', ',@userlist));
 1474: 	    } else {
 1475: 		$errormsg=&mt("An error occured while processing this resource. The instructor has been notified.");
 1476: 	    }
 1477: 	}
 1478: 	push(@Apache::lonxml::error_messages,"<b>$errormsg</b> <br />");
 1479:     }
 1480: }
 1481: 
 1482: sub warning {
 1483:     $warningcount++;
 1484:   
 1485:     if ($env{'form.grade_target'} ne 'tex') {
 1486: 	if ( &show_error_warn_msg() ) {
 1487: 	    my $request=$Apache::lonxml::request;
 1488: 	    if (!$request) { $request=Apache->request; }
 1489: 	    push(@Apache::lonxml::warning_messages,
 1490: 		 $Apache::lonxml::warnings_error_header.
 1491: 		 "<b>W</b>ARNING<b>:</b>".join('<br />',@_)."<br />\n");
 1492: 	    $Apache::lonxml::warnings_error_header='';
 1493: 	}
 1494:     }
 1495: }
 1496: 
 1497: sub info {
 1498:     if ($env{'form.grade_target'} ne 'tex' 
 1499: 	&& $env{'request.state'} eq 'construct') {
 1500: 	push(@Apache::lonxml::info_messages,join('<br />',@_)."<br />\n");
 1501:     }
 1502: }
 1503: 
 1504: sub message_location {
 1505:     return '__LONCAPA_INTERNAL_MESSAGE_LOCATION__';
 1506: }
 1507: 
 1508: sub add_messages {
 1509:     my ($msg)=@_;
 1510:     my $result=join(' ',
 1511: 		    @Apache::lonxml::info_messages,
 1512: 		    @Apache::lonxml::error_messages,
 1513: 		    @Apache::lonxml::warning_messages);
 1514:     undef(@Apache::lonxml::info_messages);
 1515:     undef(@Apache::lonxml::error_messages);
 1516:     undef(@Apache::lonxml::warning_messages);
 1517:     $$msg=~s/__LONCAPA_INTERNAL_MESSAGE_LOCATION__/$result/;
 1518:     $$msg=~s/__LONCAPA_INTERNAL_MESSAGE_LOCATION__//g;
 1519: }
 1520: 
 1521: sub get_param {
 1522:     my ($param,$parstack,$safeeval,$context,$case_insensitive) = @_;
 1523:     if ( ! $context ) { $context = -1; }
 1524:     my $args ='';
 1525:     if ( $#$parstack > (-2-$context) ) { $args=$$parstack[$context]; }
 1526:     if ( ! $Apache::lonxml::usestyle ) {
 1527: 	$args=$Apache::lonxml::style_values.$args;
 1528:     }
 1529:     if ( ! $args ) { return undef; }
 1530:     if ( $case_insensitive ) {
 1531: 	if ($args =~ s/(my \$)(\Q$param\E)(=\")/$1.lc($2).$3/ei) {
 1532: 	    return &Apache::run::run("{$args;".'return $'.$param.'}',
 1533:                                      $safeeval); #'
 1534: 	} else {
 1535: 	    return undef;
 1536: 	}
 1537:     } else {
 1538: 	if ( $args =~ /my \$\Q$param\E=\"/ ) {
 1539: 	    return &Apache::run::run("{$args;".'return $'.$param.'}',
 1540:                                      $safeeval); #'
 1541: 	} else {
 1542: 	    return undef;
 1543: 	}
 1544:     }
 1545: }
 1546: 
 1547: sub get_param_var {
 1548:   my ($param,$parstack,$safeeval,$context,$case_insensitive) = @_;
 1549:   if ( ! $context ) { $context = -1; }
 1550:   my $args ='';
 1551:   if ( $#$parstack > (-2-$context) ) { $args=$$parstack[$context]; }
 1552:   if ( ! $Apache::lonxml::usestyle ) {
 1553:       $args=$Apache::lonxml::style_values.$args;
 1554:   }
 1555:   &Apache::lonxml::debug("Args are $args param is $param");
 1556:   if ($case_insensitive) {
 1557:       if (! ($args=~s/(my \$)(\Q$param\E)(=\")/$1.lc($2).$3/ei)) {
 1558: 	  return undef;
 1559:       }
 1560:   } elsif ( $args !~ /my \$\Q$param\E=\"/ ) { return undef; }
 1561:   my $value=&Apache::run::run("{$args;".'return $'.$param.'}',$safeeval); #'
 1562:   &Apache::lonxml::debug("first run is $value");
 1563:   if ($value =~ /^[\$\@\%][a-zA-Z_]\w*$/) {
 1564:       &Apache::lonxml::debug("doing second");
 1565:       my @result=&Apache::run::run("return $value",$safeeval,1);
 1566:       if (!defined($result[0])) {
 1567: 	  return $value
 1568:       } else {
 1569: 	  if (wantarray) { return @result; } else { return $result[0]; }
 1570:       }
 1571:   } else {
 1572:     return $value;
 1573:   }
 1574: }
 1575: 
 1576: sub register_insert {
 1577:   my @data = split /\n/, &Apache::lonnet::getfile('/home/httpd/lonTabs/insertlist.tab');
 1578:   my $i;
 1579:   my $tagnum=0;
 1580:   my @order;
 1581:   for ($i=0;$i < $#data; $i++) {
 1582:     my $line = $data[$i];
 1583:     if ( $line =~ /^\#/ || $line =~ /^\s*\n/) { next; }
 1584:     if ( $line =~ /TABLE/ ) { last; }
 1585:     my ($tag,$descrip,$color,$function,$show,$helpfile,$helpdesc) = split(/,/, $line);
 1586:     if ($tag) {
 1587:       $insertlist{"$tagnum.tag"} = $tag;
 1588:       $insertlist{"$tagnum.description"} = $descrip;
 1589:       $insertlist{"$tagnum.color"} = $color;
 1590:       $insertlist{"$tagnum.function"} = $function;
 1591:       if (!defined($show)) { $show='yes'; }
 1592:       $insertlist{"$tagnum.show"}= $show;
 1593:       $insertlist{"$tagnum.helpfile"} = $helpfile;
 1594:       $insertlist{"$tagnum.helpdesc"} = $helpdesc;
 1595:       $insertlist{"$tag.num"}=$tagnum;
 1596:       $tagnum++;
 1597:     }
 1598:   }
 1599:   $i++; #skipping TABLE line
 1600:   $tagnum = 0;
 1601:   for (;$i < $#data;$i++) {
 1602:     my $line = $data[$i];
 1603:     my ($mnemonic,@which) = split(/ +/,$line);
 1604:     my $tag = $insertlist{"$tagnum.tag"};
 1605:     for (my $j=0;$j <=$#which;$j++) {
 1606:       if ( $which[$j] eq 'Y' ) {
 1607: 	if ($insertlist{"$j.show"} ne 'no') {
 1608: 	  push(@{ $insertlist{"$tag.which"} },$j);
 1609: 	}
 1610:       }
 1611:     }
 1612:     $tagnum++;
 1613:   }
 1614: }
 1615: 
 1616: sub description {
 1617:   my ($token)=@_;
 1618:   my $tagnum;
 1619:   my $tag=$token->[1];
 1620:   foreach my $namespace (reverse @Apache::lonxml::namespace) {
 1621:     my $testtag=$namespace.'::'.$tag;
 1622:     $tagnum=$insertlist{"$testtag.num"};
 1623:     if (defined($tagnum)) { last; }
 1624:   }
 1625:   if (!defined ($tagnum)) { $tagnum=$Apache::lonxml::insertlist{"$tag.num"}; }
 1626:   return $insertlist{$tagnum.'.description'};
 1627: }
 1628: 
 1629: # Returns a list containing the help file, and the description
 1630: sub helpinfo {
 1631:   my ($token)=@_;
 1632:   my $tagnum;
 1633:   my $tag=$token->[1];
 1634:   foreach my $namespace (reverse @Apache::lonxml::namespace) {
 1635:     my $testtag=$namespace.'::'.$tag;
 1636:     $tagnum=$insertlist{"$testtag.num"};
 1637:     if (defined($tagnum)) { last; }
 1638:   }
 1639:   if (!defined ($tagnum)) { $tagnum=$Apache::lonxml::insertlist{"$tag.num"}; }
 1640:   return ($insertlist{$tagnum.'.helpfile'}, $insertlist{$tagnum.'.helpdesc'});
 1641: }
 1642: 
 1643: # ----------------------------------------------------------------- whichuser
 1644: # returns a list of $symb, $courseid, $domain, $name that is correct for
 1645: # calls to lonnet functions for this setup.
 1646: # - looks for form.grade_ parameters
 1647: sub whichuser {
 1648:   my ($passedsymb)=@_;
 1649:   my ($symb,$courseid,$domain,$name,$publicuser);
 1650:   if (defined($env{'form.grade_symb'})) {
 1651:       my ($tmp_courseid)=
 1652: 	  &Apache::loncommon::get_env_multiple('form.grade_courseid');
 1653:       my $allowed=&Apache::lonnet::allowed('vgr',$tmp_courseid);
 1654:       if (!$allowed && 
 1655: 	  exists($env{'request.course.sec'}) && 
 1656: 	  $env{'request.course.sec'} !~ /^\s*$/) {
 1657: 	  $allowed=&Apache::lonnet::allowed('vgr',$tmp_courseid.
 1658: 					    '/'.$env{'request.course.sec'});
 1659:       }
 1660:       if ($allowed) {
 1661: 	  ($symb)=&Apache::loncommon::get_env_multiple('form.grade_symb');
 1662: 	  $courseid=$tmp_courseid;
 1663: 	  ($domain)=&Apache::loncommon::get_env_multiple('form.grade_domain');
 1664: 	  ($name)=&Apache::loncommon::get_env_multiple('form.grade_username');
 1665: 	  return ($symb,$courseid,$domain,$name,$publicuser);
 1666:       }
 1667:   }
 1668:   if (!$passedsymb) {
 1669:       $symb=&Apache::lonnet::symbread();
 1670:   } else {
 1671:       $symb=$passedsymb;
 1672:   }
 1673:   $courseid=$env{'request.course.id'};
 1674:   $domain=$env{'user.domain'};
 1675:   $name=$env{'user.name'};
 1676:   if ($name eq 'public' && $domain eq 'public') {
 1677:       if (!defined($env{'form.username'})) {
 1678: 	  $env{'form.username'}.=time.rand(10000000);
 1679:       }
 1680:       $name.=$env{'form.username'};
 1681:   }
 1682:   return ($symb,$courseid,$domain,$name,$publicuser);
 1683: }
 1684: 
 1685: 1;
 1686: __END__
 1687: 
 1688: 

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>