File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.408: download - view: text, annotated - select for diffs
Tue Apr 18 20:50:45 2006 UTC (18 years, 1 month ago) by albertel
Branches: MAIN
CVS tags: HEAD
- move fontsetting to be with start/end_page

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

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