File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.367: download - view: text, annotated - select for diffs
Wed Mar 23 22:02:32 2005 UTC (19 years, 2 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- escape { and } for printing
- handle strings of special symbols more correctly

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

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