File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.361: download - view: text, annotated - select for diffs
Thu Mar 10 02:34:59 2005 UTC (19 years, 3 months ago) by www
Branches: MAIN
CVS tags: HEAD
Do document-checking via ssi-call
Do not let people publish documents with errors

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

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