File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.369: download - view: text, annotated - select for diffs
Fri Apr 1 18:08:14 2005 UTC (19 years, 2 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- BUG# 2331, homework can be done in 'sequential' mode now, Only show part 2 once part 1 is correct, or unanswerable (tries exhausted)
- added new function &check_status($partid) to check the current status of a part

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

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