File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.411: download - view: text, annotated - select for diffs
Thu Apr 20 02:58:14 2006 UTC (18 years, 1 month ago) by albertel
Branches: MAIN
CVS tags: HEAD
- moving this global from lonxml into the session environment

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

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