File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.505.2.5: download - view: text, annotated - select for diffs
Fri May 27 19:29:21 2011 UTC (13 years ago) by raeburn
Branches: version_2_10_X
Diff to branchpoint 1.505: preferred, unified
- Backport 1.519.

    1: # The LearningOnline Network with CAPA
    2: # XML Parser Module 
    3: #
    4: # $Id: lonxml.pm,v 1.505.2.5 2011/05/27 19:29:21 raeburn 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: =pod
   41: 
   42: =head1 NAME
   43: 
   44: Apache::lonxml
   45: 
   46: =head1 SYNOPSIS
   47: 
   48: XML Parsing Module
   49: 
   50: This is part of the LearningOnline Network with CAPA project
   51: described at http://www.lon-capa.org.
   52: 
   53: 
   54: =head1 SUBROUTINES
   55: 
   56: =cut
   57: 
   58: 
   59: 
   60: package Apache::lonxml; 
   61: use vars 
   62: qw(@pwd @outputstack $redirection $import @extlinks $metamode $evaluate %insertlist @namespace $errorcount $warningcount);
   63: use strict;
   64: use LONCAPA;
   65: use HTML::LCParser();
   66: use HTML::TreeBuilder();
   67: use HTML::Entities();
   68: use Safe();
   69: use Safe::Hole();
   70: use Math::Cephes();
   71: use Math::Random();
   72: use Opcode();
   73: use POSIX qw(strftime);
   74: use Time::HiRes qw( gettimeofday tv_interval );
   75: use Symbol();
   76: 
   77: sub register {
   78:   my ($space,@taglist) = @_;
   79:   foreach my $temptag (@taglist) {
   80:     push(@{ $Apache::lonxml::alltags{$temptag} },$space);
   81:   }
   82: }
   83: 
   84: sub deregister {
   85:   my ($space,@taglist) = @_;
   86:   foreach my $temptag (@taglist) {
   87:     my $tempspace = $Apache::lonxml::alltags{$temptag}[-1];
   88:     if ($tempspace eq $space) {
   89:       pop(@{ $Apache::lonxml::alltags{$temptag} });
   90:     }
   91:   }
   92:   #&printalltags();
   93: }
   94: 
   95: use Apache::Constants qw(:common);
   96: use Apache::lontexconvert();
   97: use Apache::style();
   98: use Apache::run();
   99: use Apache::londefdef();
  100: use Apache::scripttag();
  101: use Apache::languagetags();
  102: use Apache::edit();
  103: use Apache::inputtags();
  104: use Apache::outputtags();
  105: use Apache::lonnet;
  106: use Apache::File();
  107: use Apache::loncommon();
  108: use Apache::lonfeedback();
  109: use Apache::lonmsg();
  110: use Apache::loncacc();
  111: use Apache::lonmaxima();
  112: use Apache::lonr();
  113: use Apache::lonlocal;
  114: use Apache::lonhtmlcommon();
  115: 
  116: #====================================   Main subroutine: xmlparse  
  117: 
  118: #debugging control, to turn on debugging modify the correct handler
  119: 
  120: $Apache::lonxml::debug=0;
  121: 
  122: # keeps count of the number of warnings and errors generated in a parse
  123: $warningcount=0;
  124: $errorcount=0;
  125: 
  126: #path to the directory containing the file currently being processed
  127: @pwd=();
  128: 
  129: #these two are used for capturing a subset of the output for later processing,
  130: #don't touch them directly use &startredirection and &endredirection
  131: @outputstack = ();
  132: $redirection = 0;
  133: 
  134: #controls wheter the <import> tag actually does
  135: $import = 1;
  136: @extlinks=();
  137: 
  138: # meta mode is a bit weird only some output is to be turned off
  139: #<output> tag turns metamode off (defined in londefdef.pm)
  140: $metamode = 0;
  141: 
  142: # turns on and of run::evaluate actually derefencing var refs
  143: $evaluate = 1;
  144: 
  145: # data structure for eidt mode, determines what tags can go into what other tags
  146: %insertlist=();
  147: 
  148: # stores the list of active tag namespaces
  149: @namespace=();
  150: 
  151: # stores all Scrit Vars displays for later showing
  152: my @script_var_displays=();
  153: 
  154: # a pointer the the Apache request object
  155: $Apache::lonxml::request='';
  156: 
  157: # a problem number counter, and check on ether it is used
  158: $Apache::lonxml::counter=1;
  159: $Apache::lonxml::counter_changed=0;
  160: 
  161: # Part counter hash.   In analysis mode, the
  162: # problems can use this to record which parts increment the counter
  163: # by how much.  The counter subs will maintain this hash via
  164: # their optional part parameters.  Note that the assumption is that
  165: # analysis is done in one request and therefore it is not necessary to
  166: # save this information request-to-request.
  167: 
  168: 
  169: %Apache::lonxml::counters_per_part = ();
  170: 
  171: #internal check on whether to look at style defs
  172: $Apache::lonxml::usestyle=1;
  173: 
  174: #locations used to store the parameter string for style substitutions
  175: $Apache::lonxml::style_values='';
  176: $Apache::lonxml::style_end_values='';
  177: 
  178: #array of ssi calls that need to occur after we are done parsing
  179: @Apache::lonxml::ssi_info=();
  180: 
  181: #should we do the postag variable interpolation
  182: $Apache::lonxml::post_evaluate=1;
  183: 
  184: #a header message to emit in the case of any generated warning or errors
  185: $Apache::lonxml::warnings_error_header='';
  186: 
  187: #  Control whether or not LaTeX symbols should be substituted for their
  188: #  \ style equivalents...this may be turned off e.g. in an verbatim
  189: #  environment.
  190: 
  191: $Apache::lonxml::substitute_LaTeX_symbols = 1; # Starts out on.
  192: 
  193: sub enable_LaTeX_substitutions {
  194:     $Apache::lonxml::substitute_LaTeX_symbols = 1;
  195: }
  196: sub disable_LaTeX_substitutions {
  197:     $Apache::lonxml::substitute_LaTeX_symbols = 0;
  198: }
  199: 
  200: sub xmlend {
  201:     my ($target,$parser)=@_;
  202:     my $mode='xml';
  203:     my $status='OPEN';
  204:     if ($Apache::lonhomework::parsing_a_problem ||
  205: 	$Apache::lonhomework::parsing_a_task ) {
  206: 	$mode='problem';
  207: 	$status=$Apache::inputtags::status[-1]; 
  208:     }
  209:     my $discussion;
  210:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
  211: 					   ['LONCAPA_INTERNAL_no_discussion']);
  212:     if (! exists($env{'form.LONCAPA_INTERNAL_no_discussion'}) ||
  213:         $env{'form.LONCAPA_INTERNAL_no_discussion'} ne 'true') {
  214:         $discussion=&Apache::lonfeedback::list_discussion($mode,$status);
  215:     }
  216:     if ($target eq 'tex') {
  217: 	$discussion.='<tex>\keephidden{ENDOFPROBLEM}\vskip 0.5mm\noindent\makebox[\textwidth/$number_of_columns][b]{\hrulefill}\end{document}</tex>';
  218: 	&Apache::lonxml::newparser($parser,\$discussion,'');
  219: 	return '';
  220:     }
  221: 
  222:     return $discussion;
  223: }
  224: 
  225: sub tokeninputfield {
  226:     my $defhost=$Apache::lonnet::perlvar{'lonHostID'};
  227:     $defhost=~tr/a-z/A-Z/;
  228:     return (<<ENDINPUTFIELD)
  229: <script type="text/javascript">
  230:     function updatetoken() {
  231: 	var comp=new Array;
  232:         var barcode=unescape(document.tokeninput.barcode.value);
  233:         comp=barcode.split('*');
  234:         if (typeof(comp[0])!="undefined") {
  235: 	    document.tokeninput.codeone.value=comp[0];
  236: 	}
  237:         if (typeof(comp[1])!="undefined") {
  238: 	    document.tokeninput.codetwo.value=comp[1];
  239: 	}
  240:         if (typeof(comp[2])!="undefined") {
  241:             comp[2]=comp[2].toUpperCase();
  242: 	    document.tokeninput.codethree.value=comp[2];
  243: 	}
  244:         document.tokeninput.barcode.value='';
  245:     }  
  246: </script>
  247: <form method="post" name="tokeninput" action="">
  248: <table border="2" bgcolor="#FFFFBB">
  249: <tr><th>DocID Checkin</th></tr>
  250: <tr><td>
  251: <table>
  252: <tr>
  253: <td>Scan in Barcode</td>
  254: <td><input type="text" size="22" name="barcode" 
  255: onchange="updatetoken()"/></td>
  256: </tr>
  257: <tr><td><i>or</i> Type in DocID</td>
  258: <td>
  259: <input type="text" size="5" name="codeone" />
  260: <b><font size="+2">*</font></b>
  261: <input type="text" size="5" name="codetwo" />
  262: <b><font size="+2">*</font></b>
  263: <input type="text" size="10" name="codethree" value="$defhost" 
  264: onchange="this.value=this.value.toUpperCase()" />
  265: </td></tr>
  266: </table>
  267: </td></tr>
  268: <tr><td><input type="submit" value="Check in DocID" /></td></tr>
  269: </table>
  270: </form>
  271: ENDINPUTFIELD
  272: }
  273: 
  274: sub maketoken {
  275:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
  276:     unless ($symb) {
  277: 	$symb=&Apache::lonnet::symbread();
  278:     }
  279:     unless ($tuname) {
  280: 	$tuname=$env{'user.name'};
  281:         $tudom=$env{'user.domain'};
  282:         $tcrsid=$env{'request.course.id'};
  283:     }
  284: 
  285:     return &Apache::lonnet::checkout($symb,$tuname,$tudom,$tcrsid);
  286: }
  287: 
  288: sub printtokenheader {
  289:     my ($target,$token,$tsymb,$tcrsid,$tudom,$tuname)=@_;
  290:     unless ($token) { return ''; }
  291: 
  292:     my ($symb,$courseid,$domain,$name) = &Apache::lonnet::whichuser();
  293:     unless ($tsymb) {
  294: 	$tsymb=$symb;
  295:     }
  296:     unless ($tuname) {
  297: 	$tuname=$name;
  298:         $tudom=$domain;
  299:         $tcrsid=$courseid;
  300:     }
  301: 
  302:     my $plainname=&Apache::loncommon::plainname($tuname,$tudom);
  303: 
  304:     if ($target eq 'web') {
  305:         my %idhash=&Apache::lonnet::idrget($tudom,($tuname));
  306: 	return 
  307:  '<img align="right" src="/cgi-bin/barcode.png?encode='.$token.'" />'.
  308:                &mt('Checked out for').' '.$plainname.
  309:                '<br />'.&mt('User').': '.$tuname.' at '.$tudom.
  310: 	       '<br />'.&mt('ID').': '.$idhash{$tuname}.
  311: 	       '<br />'.&mt('CourseID').': '.$tcrsid.
  312: 	       '<br />'.&mt('Course').': '.$env{'course.'.$tcrsid.'.description'}.
  313:                '<br />'.&mt('DocID').': '.$token.
  314:                '<br />'.&mt('Time').': '.&Apache::lonlocal::locallocaltime().'<hr />';
  315:     } else {
  316:         return $token;
  317:     }
  318: }
  319: 
  320: sub printalltags {
  321:   my $temp;
  322:   foreach $temp (sort keys %Apache::lonxml::alltags) {
  323:     &Apache::lonxml::debug("$temp -- ".
  324: 		  join(',',@{ $Apache::lonxml::alltags{$temp} }));
  325:   }
  326: }
  327: 
  328: sub xmlparse {
  329:  my ($request,$target,$content_file_string,$safeinit,%style_for_target) = @_;
  330: 
  331:  &setup_globals($request,$target);
  332:  &Apache::inputtags::initialize_inputtags();
  333:  &Apache::bridgetask::initialize_bridgetask();
  334:  &Apache::outputtags::initialize_outputtags();
  335:  &Apache::edit::initialize_edit();
  336:  &Apache::londefdef::initialize_londefdef();
  337: 
  338: #
  339: # do we have a course style file?
  340: #
  341: 
  342:  if ($env{'request.course.id'} && $env{'request.state'} ne 'construct') {
  343:      my $bodytext=
  344: 	 $env{'course.'.$env{'request.course.id'}.'.default_xml_style'};
  345:      if ($bodytext) {
  346: 	 foreach my $file (split(',',$bodytext)) {
  347: 	     my $location=&Apache::lonnet::filelocation('',$file);
  348: 	     my $styletext=&Apache::lonnet::getfile($location);
  349: 	     if ($styletext ne '-1') {
  350: 		 %style_for_target = (%style_for_target,
  351: 				      &Apache::style::styleparser($target,$styletext));
  352: 	     }
  353: 	 }
  354:      }
  355:  } elsif ($env{'construct.style'}
  356: 	  && ($env{'request.state'} eq 'construct')) {
  357:      my $location=&Apache::lonnet::filelocation('',$env{'construct.style'});
  358:      my $styletext=&Apache::lonnet::getfile($location);
  359:      if ($styletext ne '-1') {
  360: 	 %style_for_target = (%style_for_target,
  361: 			      &Apache::style::styleparser($target,$styletext));
  362:      }
  363:  }
  364: #&printalltags();
  365:  my @pars = ();
  366:  my $pwd=$env{'request.filename'};
  367:  $pwd =~ s:/[^/]*$::;
  368:  &newparser(\@pars,\$content_file_string,$pwd);
  369: 
  370:  my $safeeval = new Safe;
  371:  my $safehole = new Safe::Hole;
  372:  &init_safespace($target,$safeeval,$safehole,$safeinit);
  373: #-------------------- Redefinition of the target in the case of compound target
  374: 
  375:  ($target, my @tenta) = split('&&',$target);
  376: 
  377:  my @stack = ();
  378:  my @parstack = ();
  379:  &initdepth();
  380:  &init_alarm();
  381:  my $finaloutput = &inner_xmlparse($target,\@stack,\@parstack,\@pars,
  382: 				   $safeeval,\%style_for_target,1);
  383: 
  384:  if (@stack) {
  385:      &warning(&mt('At end of file some tags were still left unclosed:').
  386: 	      ' <tt>&lt;'.join('&gt;</tt>, <tt>&lt;',reverse(@stack)).
  387: 	      '&gt;</tt>');
  388:  }
  389:  if ($env{'request.uri'}) {
  390:     &writeallows($env{'request.uri'});
  391:  }
  392:  &do_registered_ssi();
  393:  if ($Apache::lonxml::counter_changed) { &store_counter() }
  394: 
  395:  &clean_safespace($safeeval);
  396: 
  397:  if (@script_var_displays) {
  398:      $finaloutput .= join('',@script_var_displays);
  399:      undef(@script_var_displays);
  400:  }
  401:  &init_state();
  402:  if ($env{'form.return_only_error_and_warning_counts'}) {
  403:      if ($env{'request.filename'}=~/\.(html|htm|xml)$/i) { 
  404:         my $error=&verify_html($content_file_string);
  405:         if ($error) { $errorcount++; }
  406:      }
  407:      return "$errorcount:$warningcount";
  408:  }
  409:  return $finaloutput;
  410: }
  411: 
  412: sub latex_special_symbols {
  413:     my ($string,$where)=@_;
  414:     #
  415:     #  If e.g. in verbatim mode, then don't substitute.
  416:     #  but return original string.
  417:     #
  418:     if (!($Apache::lonxml::substitute_LaTeX_symbols)) {
  419: 	return $string;
  420:     }
  421:     if ($where eq 'header') {
  422: 	$string =~ s/\\/\$\\backslash\$/g; # \  -> $\backslash$ per LaTex line by line pg  10.
  423: 	$string =~ s/(\$|%|\{|\})/\\$1/g;
  424: 	$string=&Apache::lonprintout::character_chart($string);
  425: 	# any & or # leftover should be safe to just escape
  426:         $string=~s/([^\\])\&/$1\\\&/g;
  427:         $string=~s/([^\\])\#/$1\\\#/g;
  428: 	$string =~ s/_/\\_/g;              # _ -> \_
  429: 	$string =~ s/\^/\\\^{}/g;          # ^ -> \^{} 
  430:     } else {
  431: 	$string=~s/\\/\\ensuremath{\\backslash}/g;
  432: 	$string=~s/\\\%|\%/\\\%/g;
  433: 	$string=~s/\\{|{/\\{/g;
  434: 	$string=~s/\\}|}/\\}/g;
  435: 	$string=~s/\\ensuremath\\{\\backslash\\}/\\ensuremath{\\backslash}/g;
  436: 	$string=~s/\\\$|\$/\\\$/g;
  437: 	$string=~s/\\\_|\_/\\\_/g;
  438:         $string=~s/([^\\]|^)(\~|\^)/$1\\$2\\strut /g;
  439: 	$string=~s/(>|<)/\\ensuremath\{$1\}/g; #more or less
  440: 	$string=&Apache::lonprintout::character_chart($string);
  441: 	# any & or # leftover should be safe to just escape
  442: 	$string=~s/\\\&|\&/\\\&/g;
  443: 	$string=~s/\\\#|\#/\\\#/g;
  444:         $string=~s/\|/\$\\mid\$/g;
  445: #single { or } How to escape?
  446:     }
  447:     return $string;
  448: }
  449: 
  450: sub inner_xmlparse {
  451:   my ($target,$stack,$parstack,$pars,$safeeval,$style_for_target,$start)=@_;
  452:   my $finaloutput = '';
  453:   my $result;
  454:   my $token;
  455:   my $dontpop=0;
  456:   my $startredirection = $Apache::lonxml::redirection;
  457:   while ( $#$pars > -1 ) {
  458:     while ($token = $$pars['-1']->get_token) {
  459:       if (($token->[0] eq 'T') || ($token->[0] eq 'C') ) {
  460: 	if ($metamode<1) {
  461: 	    my $text=$token->[1];
  462: 	    if ($token->[0] eq 'C' && $target eq 'tex') {
  463: 		$text = '';
  464: #		$text = '%'.$text."\n";
  465: 	    }
  466: 	    $result.=$text;
  467: 	}
  468:       } elsif (($token->[0] eq 'D')) {
  469: 	if ($metamode<1 && $target eq 'web') {
  470: 	    my $text=$token->[1];
  471: 	    $result.=$text;
  472: 	}
  473:       } elsif ($token->[0] eq 'PI') {
  474: 	if ($metamode<1 && $target eq 'web') {
  475: 	  $result=$token->[2];
  476: 	}
  477:       } elsif ($token->[0] eq 'S') {
  478: 	# add tag to stack
  479: 	push (@$stack,$token->[1]);
  480: 	# add parameters list to another stack
  481: 	push (@$parstack,&parstring($token));
  482: 	&increasedepth($token);
  483: 	if ($Apache::lonxml::usestyle &&
  484: 	    exists($$style_for_target{$token->[1]})) {
  485: 	    $Apache::lonxml::usestyle=0;
  486: 	    my $string=$$style_for_target{$token->[1]}.
  487: 	      '<LONCAPA_INTERNAL_TURN_STYLE_ON />';
  488: 	    &Apache::lonxml::newparser($pars,\$string);
  489: 	    $Apache::lonxml::style_values=$$parstack[-1];
  490: 	    $Apache::lonxml::style_end_values=$$parstack[-1];
  491: 	} else {
  492: 	  $result = &callsub("start_$token->[1]", $target, $token, $stack,
  493: 			     $parstack, $pars, $safeeval, $style_for_target);
  494: 	}
  495:       } elsif ($token->[0] eq 'E') {
  496: 	if ($Apache::lonxml::usestyle &&
  497: 	    exists($$style_for_target{'/'."$token->[1]"})) {
  498: 	    $Apache::lonxml::usestyle=0;
  499: 	    my $string=$$style_for_target{'/'.$token->[1]}.
  500: 	      '<LONCAPA_INTERNAL_TURN_STYLE_ON end="'.$token->[1].'" />';
  501: 	    &Apache::lonxml::newparser($pars,\$string);
  502: 	    $Apache::lonxml::style_values=$Apache::lonxml::style_end_values;
  503: 	    $Apache::lonxml::style_end_values='';
  504: 	    $dontpop=1;
  505: 	} else {
  506: 	    #clear out any tags that didn't end
  507: 	    while ($token->[1] ne $$stack['-1'] && ($#$stack > -1)) {
  508: 		my $lasttag=$$stack[-1];
  509: 		if ($token->[1] =~ /^\Q$lasttag\E$/i) {
  510: 		    &Apache::lonxml::warning(&mt('Using tag [_1] on line [_2] as end tag to [_3]','&lt;/'.$token->[1].'&gt;','.$token->[3].','&lt;'.$$stack[-1].'&gt;'));
  511: 		    last;
  512: 		} else {
  513:                     &Apache::lonxml::warning(&mt('Found tag [_1] on line [_2] when looking for [_3] in file.','&lt;/'.$token->[1].'&gt;',$token->[3],'&lt;/'.$$stack[-1].'&gt;'));
  514: 		    &end_tag($stack,$parstack,$token);
  515: 		}
  516: 	    }
  517: 	    $result = &callsub("end_$token->[1]", $target, $token, $stack,
  518: 			       $parstack, $pars,$safeeval, $style_for_target);
  519: 	}
  520:       } else {
  521: 	&Apache::lonxml::error("Unknown token event :$token->[0]:$token->[1]:");
  522:       }
  523:       #evaluate variable refs in result
  524:       if ($Apache::lonxml::post_evaluate &&$result ne "") {
  525: 	  my $extras;
  526: 	  if (!$Apache::lonxml::usestyle) {
  527: 	      $extras=$Apache::lonxml::style_values;
  528: 	  }
  529: 	  if ( $#$parstack > -1 ) {
  530: 	      $result=&Apache::run::evaluate($result,$safeeval,$extras.$$parstack[-1]);
  531: 	  } else {
  532: 	      $result= &Apache::run::evaluate($result,$safeeval,$extras);
  533:           }
  534:       }
  535:       $Apache::lonxml::post_evaluate=1;
  536: 
  537:       if (($token->[0] eq 'T') || ($token->[0] eq 'C') || ($token->[0] eq 'D') ) {
  538: 	  #Style file definitions should be correct
  539: 	  if ($target eq 'tex' && ($Apache::lonxml::usestyle)) {
  540: 	      $result=&latex_special_symbols($result);
  541: 	  }
  542:       }
  543: 
  544:       if ($Apache::lonxml::redirection) {
  545: 	$Apache::lonxml::outputstack['-1'] .= $result;
  546:       } else {
  547: 	$finaloutput.=$result;
  548:       }
  549:       $result = '';
  550: 
  551:       if ($token->[0] eq 'E' && !$dontpop) {
  552: 	&end_tag($stack,$parstack,$token);
  553:       }
  554:       $dontpop=0;
  555:     }	
  556:     if ($#$pars > -1) {
  557: 	pop @$pars;
  558: 	pop @Apache::lonxml::pwd;
  559:     }
  560:   }
  561: 
  562:   # if ($target eq 'meta') {
  563:   #   $finaloutput.=&endredirection;
  564:   # }
  565: 
  566:   if ( $start && $target eq 'grade') { &endredirection(); }
  567:   if ( $Apache::lonxml::redirection > $startredirection) {
  568:       while ($Apache::lonxml::redirection > $startredirection) {
  569: 	  $finaloutput .= &endredirection();
  570:       }
  571:   }
  572:   if (($ENV{'QUERY_STRING'}) && ($target eq 'web')) {
  573:     $finaloutput=&afterburn($finaloutput);
  574:   }	    
  575:   if ($target eq 'modified') {
  576: # if modfied, handle startpart and endpart
  577:      $finaloutput=~s/\<startpartmarker[^\>]*\>(.*)\<endpartmarker[^\>]*\>/<part>$1<\/part>/gs;
  578:   }
  579:   return $finaloutput;
  580: }
  581: 
  582: ## 
  583: ## Looks to see if there is a subroutine defined for this tag.  If so, call it,
  584: ## otherwise do not call it as we do not know what it is.
  585: ##
  586: sub callsub {
  587:   my ($sub,$target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  588:   my $currentstring='';
  589:   my $nodefault;
  590:   {
  591:     my $sub1;
  592:     no strict 'refs';
  593:     my $tag=$token->[1];
  594: # get utterly rid of extended html tags
  595:     if ($tag=~/^x\-/i) { return ''; }
  596:     my $space=$Apache::lonxml::alltags{$tag}[-1];
  597:     if (!$space) {
  598:      	$tag=~tr/A-Z/a-z/;
  599: 	$sub=~tr/A-Z/a-z/;
  600: 	$space=$Apache::lonxml::alltags{$tag}[-1]
  601:     }
  602: 
  603:     my $deleted=0;
  604:     if (($token->[0] eq 'S') && ($target eq 'modified')) {
  605:       $deleted=&Apache::edit::handle_delete($space,$target,$token,$tagstack,
  606: 					     $parstack,$parser,$safeeval,
  607: 					     $style);
  608:     }
  609:     if (!$deleted) {
  610:       if ($space) {
  611: 	#&Apache::lonxml::debug("Calling sub $sub in $space $metamode");
  612: 	$sub1="$space\:\:$sub";
  613: 	($currentstring,$nodefault) = &$sub1($target,$token,$tagstack,
  614: 					     $parstack,$parser,$safeeval,
  615: 					     $style);
  616:       } else {
  617:           if ($target eq 'tex') {
  618:               # throw away tag name
  619:               return '';
  620:           }
  621: 	#&Apache::lonxml::debug("NOT Calling sub $sub in $space $metamode");
  622: 	if ($metamode <1) {
  623: 	  if (defined($token->[4]) && ($metamode < 1)) {
  624: 	    $currentstring = $token->[4];
  625: 	  } else {
  626: 	    $currentstring = $token->[2];
  627: 	  }
  628: 	}
  629:       }
  630:       #    &Apache::lonxml::debug("nodefalt:$nodefault:");
  631:       if ($currentstring eq '' && $nodefault eq '') {
  632: 	if ($target eq 'edit') {
  633: 	  #&Apache::lonxml::debug("doing default edit for $token->[1]");
  634: 	  if ($token->[0] eq 'S') {
  635: 	    $currentstring = &Apache::edit::tag_start($target,$token);
  636: 	  } elsif ($token->[0] eq 'E') {
  637: 	    $currentstring = &Apache::edit::tag_end($target,$token);
  638: 	  }
  639: 	}
  640:       }
  641:       if ($target eq 'modified' && $nodefault eq '') {
  642: 	  if ($currentstring eq '') {
  643: 	      if ($token->[0] eq 'S') {
  644: 		  $currentstring = $token->[4];
  645: 	      } elsif ($token->[0] eq 'E') {
  646: 		  $currentstring = $token->[2];
  647: 	      } else {
  648: 		  $currentstring = $token->[2];
  649: 	      }
  650: 	  }
  651: 	  if ($token->[0] eq 'S') {
  652: 	      $currentstring.=&Apache::edit::handle_insert();
  653: 	  } elsif ($token->[0] eq 'E') {
  654: 	      $currentstring.=&Apache::edit::handle_insertafter($token->[1]);
  655: 	  }
  656:       }
  657:     }
  658:     use strict 'refs';
  659:   }
  660:   return $currentstring;
  661: }
  662: 
  663: {
  664:     my %state;
  665: 
  666:     sub init_state {
  667: 	undef(%state);
  668:     }
  669:     
  670:     sub set_state {
  671: 	my ($key,$value) = @_;
  672: 	$state{$key} = $value;
  673: 	return $value;
  674:     }
  675:     sub get_state {
  676: 	my ($key) = @_;
  677: 	return $state{$key};
  678:     }
  679: }
  680: 
  681: sub setup_globals {
  682:   my ($request,$target)=@_;
  683:   $Apache::lonxml::request=$request;
  684:   $errorcount=0;
  685:   $warningcount=0;
  686:   $Apache::lonxml::internal_error=0;
  687:   $Apache::lonxml::default_homework_loaded=0;
  688:   $Apache::lonxml::usestyle=1;
  689:   &init_counter();
  690:   &clear_bubble_lines_for_part();
  691:   &init_state();
  692:   &set_state('target',$target);
  693:   @Apache::lonxml::pwd=();
  694:   @Apache::lonxml::extlinks=();
  695:   @script_var_displays=();
  696:   @Apache::lonxml::ssi_info=();
  697:   $Apache::lonxml::post_evaluate=1;
  698:   $Apache::lonxml::warnings_error_header='';
  699:   $Apache::lonxml::substitute_LaTeX_symbols = 1;
  700:   if ($target eq 'meta') {
  701:     $Apache::lonxml::redirection = 0;
  702:     $Apache::lonxml::metamode = 1;
  703:     $Apache::lonxml::evaluate = 1;
  704:     $Apache::lonxml::import = 0;
  705:   } elsif ($target eq 'answer') {
  706:     $Apache::lonxml::redirection = 0;
  707:     $Apache::lonxml::metamode = 1;
  708:     $Apache::lonxml::evaluate = 1;
  709:     $Apache::lonxml::import = 1;
  710:   } elsif ($target eq 'grade') {
  711:     &startredirection(); #ended in inner_xmlparse on exit
  712:     $Apache::lonxml::metamode = 0;
  713:     $Apache::lonxml::evaluate = 1;
  714:     $Apache::lonxml::import = 1;
  715:   } elsif ($target eq 'modified') {
  716:     $Apache::lonxml::redirection = 0;
  717:     $Apache::lonxml::metamode = 0;
  718:     $Apache::lonxml::evaluate = 0;
  719:     $Apache::lonxml::import = 0;
  720:   } elsif ($target eq 'edit') {
  721:     $Apache::lonxml::redirection = 0;
  722:     $Apache::lonxml::metamode = 0;
  723:     $Apache::lonxml::evaluate = 0;
  724:     $Apache::lonxml::import = 0;
  725:   } elsif ($target eq 'analyze') {
  726:     $Apache::lonxml::redirection = 0;
  727:     $Apache::lonxml::metamode = 0;
  728:     $Apache::lonxml::evaluate = 1;
  729:     $Apache::lonxml::import = 1;
  730:   } else {
  731:     $Apache::lonxml::redirection = 0;
  732:     $Apache::lonxml::metamode = 0;
  733:     $Apache::lonxml::evaluate = 1;
  734:     $Apache::lonxml::import = 1;
  735:   }
  736: }
  737: 
  738: sub init_safespace {
  739:   my ($target,$safeeval,$safehole,$safeinit) = @_;
  740:   $safeeval->deny_only(':dangerous');
  741:   $safeeval->reval('use Math::Complex;');
  742:   $safeeval->permit_only(":default");
  743:   $safeeval->permit("entereval");
  744:   $safeeval->permit(":base_math");
  745:   $safeeval->permit("sort");
  746:   $safeeval->permit("time");
  747:   $safeeval->permit("caller");
  748:   $safeeval->deny("rand");
  749:   $safeeval->deny("srand");
  750:   $safeeval->deny(":base_io");
  751:   $safehole->wrap(\&Apache::scripttag::xmlparse,$safeeval,'&xmlparse');
  752:   $safehole->wrap(\&Apache::outputtags::multipart,$safeeval,'&multipart');
  753:   $safehole->wrap(\&Apache::lonnet::EXT,$safeeval,'&EXT');
  754:   $safehole->wrap(\&Apache::chemresponse::chem_standard_order,$safeeval,
  755: 		  '&chem_standard_order');
  756:   $safehole->wrap(\&Apache::response::check_status,$safeeval,'&check_status');
  757:   $safehole->wrap(\&Apache::response::implicit_multiplication,$safeeval,'&implicit_multiplication');
  758: 
  759:   $safehole->wrap(\&Apache::lonmaxima::maxima_eval,$safeeval,'&maxima_eval');
  760:   $safehole->wrap(\&Apache::lonmaxima::maxima_check,$safeeval,'&maxima_check');
  761:   $safehole->wrap(\&Apache::lonmaxima::maxima_cas_formula_fix,$safeeval,
  762: 		  '&maxima_cas_formula_fix');
  763: 
  764:   $safehole->wrap(\&Apache::lonr::r_eval,$safeeval,'&r_eval');
  765:   $safehole->wrap(\&Apache::lonr::Rentry,$safeeval,'&Rentry');
  766:   $safehole->wrap(\&Apache::lonr::Rarray,$safeeval,'&Rarray');
  767:   $safehole->wrap(\&Apache::lonr::r_check,$safeeval,'&r_check');
  768:   $safehole->wrap(\&Apache::lonr::r_cas_formula_fix,$safeeval,
  769:                   '&r_cas_formula_fix');
  770:  
  771:   $safehole->wrap(\&Apache::caparesponse::capa_formula_fix,$safeeval,
  772: 		  '&capa_formula_fix');
  773: 
  774:   $safehole->wrap(\&Apache::lonlocal::locallocaltime,$safeeval,
  775:                   '&locallocaltime');
  776: 
  777:   $safehole->wrap(\&Math::Cephes::asin,$safeeval,'&asin');
  778:   $safehole->wrap(\&Math::Cephes::acos,$safeeval,'&acos');
  779:   $safehole->wrap(\&Math::Cephes::atan,$safeeval,'&atan');
  780:   $safehole->wrap(\&Math::Cephes::sinh,$safeeval,'&sinh');
  781:   $safehole->wrap(\&Math::Cephes::cosh,$safeeval,'&cosh');
  782:   $safehole->wrap(\&Math::Cephes::tanh,$safeeval,'&tanh');
  783:   $safehole->wrap(\&Math::Cephes::asinh,$safeeval,'&asinh');
  784:   $safehole->wrap(\&Math::Cephes::acosh,$safeeval,'&acosh');
  785:   $safehole->wrap(\&Math::Cephes::atanh,$safeeval,'&atanh');
  786:   $safehole->wrap(\&Math::Cephes::erf,$safeeval,'&erf');
  787:   $safehole->wrap(\&Math::Cephes::erfc,$safeeval,'&erfc');
  788:   $safehole->wrap(\&Math::Cephes::j0,$safeeval,'&j0');
  789:   $safehole->wrap(\&Math::Cephes::j1,$safeeval,'&j1');
  790:   $safehole->wrap(\&Math::Cephes::jn,$safeeval,'&jn');
  791:   $safehole->wrap(\&Math::Cephes::jv,$safeeval,'&jv');
  792:   $safehole->wrap(\&Math::Cephes::y0,$safeeval,'&y0');
  793:   $safehole->wrap(\&Math::Cephes::y1,$safeeval,'&y1');
  794:   $safehole->wrap(\&Math::Cephes::yn,$safeeval,'&yn');
  795:   $safehole->wrap(\&Math::Cephes::yv,$safeeval,'&yv');
  796:   
  797:   $safehole->wrap(\&Math::Cephes::bdtr  ,$safeeval,'&bdtr'  );
  798:   $safehole->wrap(\&Math::Cephes::bdtrc ,$safeeval,'&bdtrc' );
  799:   $safehole->wrap(\&Math::Cephes::bdtri ,$safeeval,'&bdtri' );
  800:   $safehole->wrap(\&Math::Cephes::btdtr ,$safeeval,'&btdtr' );
  801:   $safehole->wrap(\&Math::Cephes::chdtr ,$safeeval,'&chdtr' );
  802:   $safehole->wrap(\&Math::Cephes::chdtrc,$safeeval,'&chdtrc');
  803:   $safehole->wrap(\&Math::Cephes::chdtri,$safeeval,'&chdtri');
  804:   $safehole->wrap(\&Math::Cephes::fdtr  ,$safeeval,'&fdtr'  );
  805:   $safehole->wrap(\&Math::Cephes::fdtrc ,$safeeval,'&fdtrc' );
  806:   $safehole->wrap(\&Math::Cephes::fdtri ,$safeeval,'&fdtri' );
  807:   $safehole->wrap(\&Math::Cephes::gdtr  ,$safeeval,'&gdtr'  );
  808:   $safehole->wrap(\&Math::Cephes::gdtrc ,$safeeval,'&gdtrc' );
  809:   $safehole->wrap(\&Math::Cephes::nbdtr ,$safeeval,'&nbdtr' );
  810:   $safehole->wrap(\&Math::Cephes::nbdtrc,$safeeval,'&nbdtrc');
  811:   $safehole->wrap(\&Math::Cephes::nbdtri,$safeeval,'&nbdtri');
  812:   $safehole->wrap(\&Math::Cephes::ndtr  ,$safeeval,'&ndtr'  );
  813:   $safehole->wrap(\&Math::Cephes::ndtri ,$safeeval,'&ndtri' );
  814:   $safehole->wrap(\&Math::Cephes::pdtr  ,$safeeval,'&pdtr'  );
  815:   $safehole->wrap(\&Math::Cephes::pdtrc ,$safeeval,'&pdtrc' );
  816:   $safehole->wrap(\&Math::Cephes::pdtri ,$safeeval,'&pdtri' );
  817:   $safehole->wrap(\&Math::Cephes::stdtr ,$safeeval,'&stdtr' );
  818:   $safehole->wrap(\&Math::Cephes::stdtri,$safeeval,'&stdtri');
  819: 
  820:   $safehole->wrap(\&Math::Cephes::Matrix::mat,$safeeval,'&mat');
  821:   $safehole->wrap(\&Math::Cephes::Matrix::new,$safeeval,
  822: 		  '&Math::Cephes::Matrix::new');
  823:   $safehole->wrap(\&Math::Cephes::Matrix::coef,$safeeval,
  824: 		  '&Math::Cephes::Matrix::coef');
  825:   $safehole->wrap(\&Math::Cephes::Matrix::clr,$safeeval,
  826: 		  '&Math::Cephes::Matrix::clr');
  827:   $safehole->wrap(\&Math::Cephes::Matrix::add,$safeeval,
  828: 		  '&Math::Cephes::Matrix::add');
  829:   $safehole->wrap(\&Math::Cephes::Matrix::sub,$safeeval,
  830: 		  '&Math::Cephes::Matrix::sub');
  831:   $safehole->wrap(\&Math::Cephes::Matrix::mul,$safeeval,
  832: 		  '&Math::Cephes::Matrix::mul');
  833:   $safehole->wrap(\&Math::Cephes::Matrix::div,$safeeval,
  834: 		  '&Math::Cephes::Matrix::div');
  835:   $safehole->wrap(\&Math::Cephes::Matrix::inv,$safeeval,
  836: 		  '&Math::Cephes::Matrix::inv');
  837:   $safehole->wrap(\&Math::Cephes::Matrix::transp,$safeeval,
  838: 		  '&Math::Cephes::Matrix::transp');
  839:   $safehole->wrap(\&Math::Cephes::Matrix::simq,$safeeval,
  840: 		  '&Math::Cephes::Matrix::simq');
  841:   $safehole->wrap(\&Math::Cephes::Matrix::mat_to_vec,$safeeval,
  842: 		  '&Math::Cephes::Matrix::mat_to_vec');
  843:   $safehole->wrap(\&Math::Cephes::Matrix::vec_to_mat,$safeeval,
  844: 		  '&Math::Cephes::Matrix::vec_to_mat');
  845:   $safehole->wrap(\&Math::Cephes::Matrix::check,$safeeval,
  846: 		  '&Math::Cephes::Matrix::check');
  847:   $safehole->wrap(\&Math::Cephes::Matrix::check,$safeeval,
  848: 		  '&Math::Cephes::Matrix::check');
  849: 
  850: #  $safehole->wrap(\&Math::Cephes::new_fract,$safeeval,'&new_fract');
  851: #  $safehole->wrap(\&Math::Cephes::radd,$safeeval,'&radd');
  852: #  $safehole->wrap(\&Math::Cephes::rsub,$safeeval,'&rsub');
  853: #  $safehole->wrap(\&Math::Cephes::rmul,$safeeval,'&rmul');
  854: #  $safehole->wrap(\&Math::Cephes::rdiv,$safeeval,'&rdiv');
  855: #  $safehole->wrap(\&Math::Cephes::euclid,$safeeval,'&euclid');
  856: 
  857:   $safehole->wrap(\&Math::Random::random_beta,$safeeval,'&math_random_beta');
  858:   $safehole->wrap(\&Math::Random::random_chi_square,$safeeval,'&math_random_chi_square');
  859:   $safehole->wrap(\&Math::Random::random_exponential,$safeeval,'&math_random_exponential');
  860:   $safehole->wrap(\&Math::Random::random_f,$safeeval,'&math_random_f');
  861:   $safehole->wrap(\&Math::Random::random_gamma,$safeeval,'&math_random_gamma');
  862:   $safehole->wrap(\&Math::Random::random_multivariate_normal,$safeeval,'&math_random_multivariate_normal');
  863:   $safehole->wrap(\&Math::Random::random_multinomial,$safeeval,'&math_random_multinomial');
  864:   $safehole->wrap(\&Math::Random::random_noncentral_chi_square,$safeeval,'&math_random_noncentral_chi_square');
  865:   $safehole->wrap(\&Math::Random::random_noncentral_f,$safeeval,'&math_random_noncentral_f');
  866:   $safehole->wrap(\&Math::Random::random_normal,$safeeval,'&math_random_normal');
  867:   $safehole->wrap(\&Math::Random::random_permutation,$safeeval,'&math_random_permutation');
  868:   $safehole->wrap(\&Math::Random::random_permuted_index,$safeeval,'&math_random_permuted_index');
  869:   $safehole->wrap(\&Math::Random::random_uniform,$safeeval,'&math_random_uniform');
  870:   $safehole->wrap(\&Math::Random::random_poisson,$safeeval,'&math_random_poisson');
  871:   $safehole->wrap(\&Math::Random::random_uniform_integer,$safeeval,'&math_random_uniform_integer');
  872:   $safehole->wrap(\&Math::Random::random_negative_binomial,$safeeval,'&math_random_negative_binomial');
  873:   $safehole->wrap(\&Math::Random::random_binomial,$safeeval,'&math_random_binomial');
  874:   $safehole->wrap(\&Math::Random::random_seed_from_phrase,$safeeval,'&random_seed_from_phrase');
  875:   $safehole->wrap(\&Math::Random::random_set_seed_from_phrase,$safeeval,'&random_set_seed_from_phrase');
  876:   $safehole->wrap(\&Math::Random::random_get_seed,$safeeval,'&random_get_seed');
  877:   $safehole->wrap(\&Math::Random::random_set_seed,$safeeval,'&random_set_seed');
  878:   $safehole->wrap(\&Apache::loncommon::languages,$safeeval,'&languages');
  879:   $safehole->wrap(\&Apache::lonxml::error,$safeeval,'&LONCAPA_INTERNAL_ERROR');
  880:   $safehole->wrap(\&Apache::lonxml::debug,$safeeval,'&LONCAPA_INTERNAL_DEBUG');
  881:   $safehole->wrap(\&Apache::lonnet::logthis,$safeeval,'&LONCAPA_INTERNAL_LOGTHIS');
  882:   $safehole->wrap(\&Apache::inputtags::finalizeawards,$safeeval,'&LONCAPA_INTERNAL_FINALIZEAWARDS');
  883:   $safehole->wrap(\&Apache::caparesponse::get_sigrange,$safeeval,'&LONCAPA_INTERNAL_get_sigrange');
  884: #  use Data::Dumper;
  885: #  $safehole->wrap(\&Data::Dumper::Dumper,$safeeval,'&LONCAPA_INTERNAL_Dumper');
  886: #need to inspect this class of ops
  887: # $safeeval->deny(":base_orig");
  888:   $safeeval->permit("require");
  889:   $safeinit .= ';$external::target="'.$target.'";';
  890:   &Apache::run::run($safeinit,$safeeval);
  891:   &initialize_rndseed($safeeval);
  892: }
  893: 
  894: sub clean_safespace {
  895:     my ($safeeval) = @_;
  896:     delete_package_recurse($safeeval->{Root});
  897: }
  898: 
  899: sub delete_package_recurse {
  900:      my ($package) = @_;
  901:      my @subp;
  902:      {
  903: 	 no strict 'refs';
  904: 	 while (my ($key,$val) = each(%{*{"$package\::"}})) {
  905: 	     if (!defined($val)) { next; }
  906: 	     local (*ENTRY) = $val;
  907: 	     if (defined *ENTRY{HASH} && $key =~ /::$/ &&
  908: 		 $key ne "main::" && $key ne "<none>::")
  909: 	     {
  910: 		 my ($p) = $package ne "main" ? "$package\::" : "";
  911: 		 ($p .= $key) =~ s/::$//;
  912: 		 push(@subp,$p);
  913: 	     }
  914: 	 }
  915:      }
  916:      foreach my $p (@subp) {
  917: 	 delete_package_recurse($p);
  918:      }
  919:      Symbol::delete_package($package);
  920: }
  921: 
  922: sub initialize_rndseed {
  923:     my ($safeeval)=@_;
  924:     my $rndseed;
  925:     my ($symb,$courseid,$domain,$name) = &Apache::lonnet::whichuser();
  926:     $rndseed=&Apache::lonnet::rndseed($symb,$courseid,$domain,$name);
  927:     my $safeinit = '$external::randomseed="'.$rndseed.'";';
  928:     &Apache::lonxml::debug("Setting rndseed to $rndseed");
  929:     &Apache::run::run($safeinit,$safeeval);
  930: }
  931: 
  932: sub default_homework_load {
  933:     my ($safeeval)=@_;
  934:     &Apache::lonxml::debug('Loading default_homework');
  935:     my $default=&Apache::lonnet::getfile('/home/httpd/html/res/adm/includes/default_homework.lcpm');
  936:     if ($default eq -1) {
  937: 	&Apache::lonxml::error("<b>Unable to find <i>default_homework.lcpm</i></b>");
  938:     } else {
  939: 	&Apache::run::run($default,$safeeval);
  940: 	$Apache::lonxml::default_homework_loaded=1;
  941:     }
  942: }
  943: 
  944: {
  945:     my $alarm_depth;
  946:     sub init_alarm {
  947: 	alarm(0);
  948: 	$alarm_depth=0;
  949:     }
  950: 
  951:     sub start_alarm {
  952: 	if ($alarm_depth<1) {
  953: 	    my $old=alarm($Apache::lonnet::perlvar{'lonScriptTimeout'});
  954: 	    if ($old) {
  955: 		&Apache::lonxml::error("Cancelled an alarm of $old, this shouldn't occur.");
  956: 	    }
  957: 	}
  958: 	$alarm_depth++;
  959:     }
  960: 
  961:     sub end_alarm {
  962: 	$alarm_depth--;
  963: 	if ($alarm_depth<1) { alarm(0); }
  964:     }
  965: }
  966: my $metamode_was;
  967: sub startredirection {
  968:     if (!$Apache::lonxml::redirection) {
  969: 	$metamode_was=$Apache::lonxml::metamode;
  970:     }
  971:     $Apache::lonxml::metamode=0;
  972:     $Apache::lonxml::redirection++;
  973:     push (@Apache::lonxml::outputstack, '');
  974: }
  975: 
  976: sub endredirection {
  977:     if (!$Apache::lonxml::redirection) {
  978: 	&Apache::lonxml::error("Endredirection was called before a startredirection, perhaps you have unbalanced tags. Some debugging information:".join ":",caller);
  979: 	return '';
  980:     }
  981:     $Apache::lonxml::redirection--;
  982:     if (!$Apache::lonxml::redirection) {
  983: 	$Apache::lonxml::metamode=$metamode_was;
  984:     }
  985:     pop @Apache::lonxml::outputstack;
  986: }
  987: sub in_redirection {
  988:     return ($Apache::lonxml::redirection > 0)
  989: }
  990: 
  991: sub end_tag {
  992:   my ($tagstack,$parstack,$token)=@_;
  993:   pop(@$tagstack);
  994:   pop(@$parstack);
  995:   &decreasedepth($token);
  996: }
  997: 
  998: sub initdepth {
  999:   @Apache::lonxml::depthcounter=();
 1000:   undef($Apache::lonxml::last_depth_count);
 1001: }
 1002: 
 1003: 
 1004: my @timers;
 1005: my $lasttime;
 1006: # @Apache::lonxml::depthcounter -> count of tags that exist so
 1007: #                                  far at each level
 1008: # $Apache::lonxml::last_depth_count -> when ascending, need to
 1009: # remember the count for the level below the current level (for
 1010: # example going from 1_2 -> 1 -> 1_3 need to remember the 2 )
 1011: 
 1012: sub increasedepth {
 1013:   my ($token) = @_;
 1014:   push(@Apache::lonxml::depthcounter,$Apache::lonxml::last_depth_count+1);
 1015:   undef($Apache::lonxml::last_depth_count);
 1016:   my $time;
 1017:   if ($Apache::lonxml::debug eq "1") {
 1018:       push(@timers,[&gettimeofday()]);
 1019:       $time=&tv_interval($lasttime);
 1020:       $lasttime=[&gettimeofday()];
 1021:   }
 1022:   my $spacing='  'x($#Apache::lonxml::depthcounter);
 1023:   $Apache::lonxml::curdepth=join('_',@Apache::lonxml::depthcounter);
 1024: #  &Apache::lonxml::debug("s$spacing$Apache::lonxml::depth : $Apache::lonxml::olddepth : $Apache::lonxml::curdepth : $token->[1] : $time");
 1025: #print "<br />s $Apache::lonxml::depth : $Apache::lonxml::olddepth : $curdepth : $token->[1]\n";
 1026: }
 1027: 
 1028: sub decreasedepth {
 1029:   my ($token) = @_;
 1030:   if (  $#Apache::lonxml::depthcounter == -1) {
 1031:       &Apache::lonxml::warning(&mt("Missing tags, unable to properly run file."));
 1032:   }
 1033:   $Apache::lonxml::last_depth_count = pop(@Apache::lonxml::depthcounter);
 1034: 
 1035:   my ($timer,$time);
 1036:   if ($Apache::lonxml::debug eq "1") {
 1037:       $timer=pop(@timers);
 1038:       $time=&tv_interval($lasttime);
 1039:       $lasttime=[&gettimeofday()];
 1040:   }
 1041:   my $spacing='  'x($#Apache::lonxml::depthcounter);
 1042:   $Apache::lonxml::curdepth = join('_',@Apache::lonxml::depthcounter);
 1043: #  &Apache::lonxml::debug("e$spacing$Apache::lonxml::depth : $Apache::lonxml::olddepth : $Apache::lonxml::curdepth : $token->[1] : $time : ".&tv_interval($timer));
 1044: #print "<br />e $Apache::lonxml::depth : $Apache::lonxml::olddepth : $token->[1] : $curdepth\n";
 1045: }
 1046: 
 1047: sub get_id {
 1048:     my ($parstack,$safeeval)=@_;
 1049:     my $id= &Apache::lonxml::get_param('id',$parstack,$safeeval);
 1050:     if ($env{'request.state'} eq 'construct' && $id =~ /([._]|[^\w\d\s[:punct:]])/) {
 1051: 	&error(&mt('ID [_1] contains invalid characters. IDs are only allowed to contain letters, numbers, spaces and -','"<tt>'.$id.'</tt>"'));
 1052:     }
 1053:     if ($id =~ /^\s*$/) { $id = $Apache::lonxml::curdepth; }
 1054:     return $id;
 1055: }
 1056: 
 1057: sub get_all_text_unbalanced {
 1058: #there is a copy of this in lonpublisher.pm
 1059:     my($tag,$pars)= @_;
 1060:     my $token;
 1061:     my $result='';
 1062:     $tag='<'.$tag.'>';
 1063:     while ($token = $$pars[-1]->get_token) {
 1064: 	if (($token->[0] eq 'T')||($token->[0] eq 'C')||($token->[0] eq 'D')) {
 1065: 	    if ($token->[0] eq 'T' && $token->[2]) {
 1066: 		$result.='<![CDATA['.$token->[1].']]>';
 1067: 	    } else {
 1068: 		$result.=$token->[1];
 1069: 	    }
 1070: 	} elsif ($token->[0] eq 'PI') {
 1071: 	    $result.=$token->[2];
 1072: 	} elsif ($token->[0] eq 'S') {
 1073: 	    $result.=$token->[4];
 1074: 	} elsif ($token->[0] eq 'E')  {
 1075: 	    $result.=$token->[2];
 1076: 	}
 1077: 	if ($result =~ /\Q$tag\E/is) {
 1078: 	    ($result,my $redo)=$result =~ /(.*)\Q$tag\E(.*)/is;
 1079: 	    #&Apache::lonxml::debug('Got a winner with leftovers ::'.$2);
 1080: 	    #&Apache::lonxml::debug('Result is :'.$1);
 1081: 	    $redo=$tag.$redo;
 1082: 	    &Apache::lonxml::newparser($pars,\$redo);
 1083: 	    last;
 1084: 	}
 1085:     }
 1086:     return $result
 1087: 
 1088: }
 1089: 
 1090: #########################################################################
 1091: #                                                                       #
 1092: #           bubble line counter management                              #
 1093: #                                                                       #
 1094: #########################################################################
 1095: 
 1096: =pod
 1097: 
 1098: For bubble grading mode and exam bubble printing mode, the tracking of
 1099: the current 'bubble line number' is stored in the %env element
 1100: 'form.counter', and is modifed and handled by the following routines.
 1101: 
 1102: The value of it is stored in $Apache:lonxml::counter when live and
 1103: stored back to env after done.
 1104: 
 1105: =item &increment_counter($increment);
 1106: 
 1107: Increments the internal counter environment variable a specified amount
 1108: 
 1109: Optional Arguments:
 1110:   $increment - amount to increment by (defaults to 1)
 1111:                Also 1 if the value is negative or zero.
 1112:   $part_response - A concatenation of the part and response id
 1113:                    identifying exactly what is being 'answered'.
 1114: 
 1115: 
 1116: =cut
 1117: 
 1118: sub increment_counter {
 1119:     my ($increment, $part_response) = @_;
 1120:     if ($env{'form.grade_noincrement'}) { return; }
 1121:     if (!defined($increment) || $increment le 0) {
 1122: 	$increment = 1;
 1123:     }
 1124:     $Apache::lonxml::counter += $increment;
 1125: 
 1126:     # If the caller supplied the response_id parameter, 
 1127:     # Maintain its counter.. creating if necessary.
 1128: 
 1129:     if (defined($part_response)) {
 1130: 	if (!defined($Apache::lonxml::counters_per_part{$part_response})) {
 1131: 	    $Apache::lonxml::counters_per_part{$part_response} = 0;
 1132: 	}
 1133: 	$Apache::lonxml::counters_per_part{$part_response} += $increment;
 1134: 	my $new_value = $Apache::lonxml::counters_per_part{$part_response};
 1135:     }
 1136: 	
 1137:     $Apache::lonxml::counter_changed=1;
 1138: }
 1139: 
 1140: =pod
 1141: 
 1142: =item &init_counter($increment);
 1143: 
 1144: Initialize the internal counter environment variable
 1145: 
 1146: =cut
 1147: 
 1148: sub init_counter {
 1149:     if ($env{'request.state'} eq 'construct') {
 1150: 	$Apache::lonxml::counter=1;
 1151: 	$Apache::lonxml::counter_changed=1;
 1152:     } elsif (defined($env{'form.counter'})) {
 1153: 	$Apache::lonxml::counter=$env{'form.counter'};
 1154: 	$Apache::lonxml::counter_changed=0;
 1155:     } else {
 1156: 	$Apache::lonxml::counter=1;
 1157: 	$Apache::lonxml::counter_changed=1;
 1158:     }
 1159: }
 1160: 
 1161: sub store_counter {
 1162:     &Apache::lonnet::appenv({'form.counter' => $Apache::lonxml::counter});
 1163:     $Apache::lonxml::counter_changed=0;
 1164:     return '';
 1165: }
 1166: 
 1167: {
 1168:     my $state;
 1169:     sub clear_problem_counter {
 1170: 	undef($state);
 1171: 	&Apache::lonnet::delenv('form.counter');
 1172: 	&Apache::lonxml::init_counter();
 1173: 	&Apache::lonxml::store_counter();
 1174:     }
 1175: 
 1176:     sub remember_problem_counter {
 1177: 	&Apache::lonnet::transfer_profile_to_env(undef,undef,1);
 1178: 	$state = $env{'form.counter'};
 1179:     }
 1180: 
 1181:     sub restore_problem_counter {
 1182: 	if (defined($state)) {
 1183: 	    &Apache::lonnet::appenv({'form.counter' => $state});
 1184: 	}
 1185:     }
 1186:     sub get_problem_counter {
 1187: 	if ($Apache::lonxml::counter_changed) { &store_counter() }
 1188: 	&Apache::lonnet::transfer_profile_to_env(undef,undef,1);
 1189: 	return $env{'form.counter'};
 1190:     }
 1191: }
 1192: 
 1193: =pod
 1194: 
 1195: =item  bubble_lines_for_part(part_response)
 1196: 
 1197: Returns the number of lines required to get a response for
 1198: $part_response (this is just $Apache::lonxml::counters_per_part{$part_response}
 1199: 
 1200: =cut
 1201: 
 1202: sub bubble_lines_for_part {
 1203:     my ($part_response) = @_;
 1204: 
 1205:     if (!defined($Apache::lonxml::counters_per_part{$part_response})) {
 1206: 	return 0;
 1207:     } else {
 1208: 	return $Apache::lonxml::counters_per_part{$part_response};
 1209:     }
 1210: }
 1211: 
 1212: =pod
 1213: 
 1214: =item clear_bubble_lines_for_part
 1215: 
 1216: Clears the hash of bubble lines per part.  If a caller
 1217: needs to analyze several resources this should be called between
 1218: resources to reset the hash for each problem being analyzed.
 1219: 
 1220: =cut
 1221: 
 1222: sub clear_bubble_lines_for_part {
 1223:     undef(%Apache::lonxml::counters_per_part);
 1224: }
 1225: 
 1226: =pod
 1227: 
 1228: =item set_bubble_lines(part_response, value)
 1229: 
 1230: If there is a problem part, that for whatever reason
 1231: requires bubble lines that are not
 1232: the same as the counter increment, it can call this sub during
 1233: analysis to set its hash value explicitly.
 1234: 
 1235: =cut
 1236: 
 1237: sub set_bubble_lines {
 1238:     my ($part_response, $value) = @_;
 1239: 
 1240:     $Apache::lonxml::counters_per_part{$part_response} = $value;
 1241: }
 1242: 
 1243: =pod
 1244: 
 1245: =item get_bubble_line_hash
 1246: 
 1247: Returns the current bubble line hash.  This is assumed to 
 1248: be small so we return a copy
 1249: 
 1250: 
 1251: =cut
 1252: 
 1253: sub get_bubble_line_hash {
 1254:     return %Apache::lonxml::counters_per_part;
 1255: }
 1256: 
 1257: 
 1258: #--------------------------------------------------
 1259: 
 1260: sub get_all_text {
 1261:     my($tag,$pars,$style)= @_;
 1262:     my $gotfullstack=1;
 1263:     if (ref($pars) ne 'ARRAY') {
 1264: 	$gotfullstack=0;
 1265: 	$pars=[$pars];
 1266:     }
 1267:     if (ref($style) ne 'HASH') {
 1268: 	$style={};
 1269:     }
 1270:     my $depth=0;
 1271:     my $token;
 1272:     my $result='';
 1273:     if ( $tag =~ m:^/: ) { 
 1274: 	my $tag=substr($tag,1); 
 1275: 	#&Apache::lonxml::debug("have:$tag:");
 1276: 	my $top_empty=0;
 1277: 	while (($depth >=0) && ($#$pars > -1) && (!$top_empty)) {
 1278: 	    while (($depth >=0) && ($token = $$pars[-1]->get_token)) {
 1279: 		#&Apache::lonxml::debug("e token:$token->[0]:$depth:$token->[1]:".$#$pars.":".$#Apache::lonxml::pwd);
 1280: 		if (($token->[0] eq 'T')||($token->[0] eq 'C')||($token->[0] eq 'D')) {
 1281: 		    if ($token->[2]) {
 1282: 			$result.='<![CDATA['.$token->[1].']]>';
 1283: 		    } else {
 1284: 			$result.=$token->[1];
 1285: 		    }
 1286: 		} elsif ($token->[0] eq 'PI') {
 1287: 		    $result.=$token->[2];
 1288: 		} elsif ($token->[0] eq 'S') {
 1289: 		    if ($token->[1] =~ /^\Q$tag\E$/i) { $depth++; }
 1290: 		    if ($token->[1] =~ /^LONCAPA_INTERNAL_TURN_STYLE_ON$/) { $Apache::lonxml::usestyle=1; }
 1291: 		    if ($token->[1] =~ /^LONCAPA_INTERNAL_TURN_STYLE_OFF$/) { $Apache::lonxml::usestyle=0; }
 1292: 		    $result.=$token->[4];
 1293: 		} elsif ($token->[0] eq 'E')  {
 1294: 		    if ( $token->[1] =~ /^\Q$tag\E$/i) { $depth--; }
 1295: 		    #skip sending back the last end tag
 1296: 		    if ($depth == 0 && exists($$style{'/'.$token->[1]}) && $Apache::lonxml::usestyle) {
 1297: 			my $string=
 1298: 			    '<LONCAPA_INTERNAL_TURN_STYLE_OFF end="yes" />'.
 1299: 				$$style{'/'.$token->[1]}.
 1300: 				    $token->[2].
 1301: 					'<LONCAPA_INTERNAL_TURN_STYLE_ON />';
 1302: 			&Apache::lonxml::newparser($pars,\$string);
 1303: 			#&Apache::lonxml::debug("reParsing $string");
 1304: 			next;
 1305: 		    }
 1306: 		    if ($depth > -1) {
 1307: 			$result.=$token->[2];
 1308: 		    } else {
 1309: 			$$pars[-1]->unget_token($token);
 1310: 		    }
 1311: 		}
 1312: 	    }
 1313: 	    if (($depth >=0) && ($#$pars == 0) ) { $top_empty=1; }
 1314: 	    if (($depth >=0) && ($#$pars > 0) ) {
 1315: 		pop(@$pars);
 1316: 		pop(@Apache::lonxml::pwd);
 1317: 	    }
 1318: 	}
 1319: 	if ($top_empty && $depth >= 0) {
 1320: 	    #never found the end tag ran out of text, throw error send back blank
 1321: 	    &error('Never found end tag for &lt;'.$tag.
 1322: 		   '&gt; current string <pre>'.
 1323: 		   &HTML::Entities::encode($result,'<>&"').
 1324: 		   '</pre>');
 1325: 	    if ($gotfullstack) {
 1326: 		my $newstring='</'.$tag.'>'.$result;
 1327: 		&Apache::lonxml::newparser($pars,\$newstring);
 1328: 	    }
 1329: 	    $result='';
 1330: 	}
 1331:     } else {
 1332: 	while ($#$pars > -1) {
 1333: 	    while ($token = $$pars[-1]->get_token) {
 1334: 		#&Apache::lonxml::debug("s token:$token->[0]:$depth:$token->[1]");
 1335: 		if (($token->[0] eq 'T')||($token->[0] eq 'C')||
 1336: 		    ($token->[0] eq 'D')) {
 1337: 		    if ($token->[2]) {
 1338: 			$result.='<![CDATA['.$token->[1].']]>';
 1339: 		    } else {
 1340: 			$result.=$token->[1];
 1341: 		    }
 1342: 		} elsif ($token->[0] eq 'PI') {
 1343: 		    $result.=$token->[2];
 1344: 		} elsif ($token->[0] eq 'S') {
 1345: 		    if ( $token->[1] =~ /^\Q$tag\E$/i) {
 1346: 			$$pars[-1]->unget_token($token); last;
 1347: 		    } else {
 1348: 			$result.=$token->[4];
 1349: 		    }
 1350: 		    if ($token->[1] =~ /^LONCAPA_INTERNAL_TURN_STYLE_ON$/) { $Apache::lonxml::usestyle=1; }
 1351: 		    if ($token->[1] =~ /^LONCAPA_INTERNAL_TURN_STYLE_OFF$/) { $Apache::lonxml::usestyle=0; }
 1352: 		} elsif ($token->[0] eq 'E')  {
 1353: 		    $result.=$token->[2];
 1354: 		}
 1355: 	    }
 1356: 	    if (($#$pars > 0) ) {
 1357: 		pop(@$pars);
 1358: 		pop(@Apache::lonxml::pwd);
 1359: 	    } else { last; }
 1360: 	}
 1361:     }
 1362:     #&Apache::lonxml::debug("Exit:$result:");
 1363:     return $result
 1364: }
 1365: 
 1366: sub newparser {
 1367:   my ($parser,$contentref,$dir) = @_;
 1368:   push (@$parser,HTML::LCParser->new($contentref));
 1369:   $$parser[-1]->xml_mode(1);
 1370:   $$parser[-1]->marked_sections(1);
 1371:   if ( $dir eq '' ) {
 1372:     push (@Apache::lonxml::pwd, $Apache::lonxml::pwd[$#Apache::lonxml::pwd]);
 1373:   } else {
 1374:     push (@Apache::lonxml::pwd, $dir);
 1375:   } 
 1376: }
 1377: 
 1378: sub parstring {
 1379:     my ($token) = @_;
 1380:     my (@vars,@values);
 1381:     foreach my $attr (@{$token->[3]}) {
 1382: 	if ($attr!~/\W/) {
 1383: 	    my $val=$token->[2]->{$attr};
 1384: 	    $val =~ s/([\%\@\\\"\'])/\\$1/g;
 1385: 	    $val =~ s/(\$[^\{a-zA-Z_])/\\$1/g;
 1386: 	    $val =~ s/(\$)$/\\$1/;
 1387: 	    #if ($val =~ m/^[\%\@]/) { $val="\\".$val; }
 1388: 	    push(@vars,"\$$attr");
 1389: 	    push(@values,"\"$val\"");
 1390: 	}
 1391:     }
 1392:     my $var_init = 
 1393: 	(@vars) ? 'my ('.join(',',@vars).') = ('.join(',',@values).');'
 1394: 	        : '';
 1395:     return $var_init;
 1396: }
 1397: 
 1398: sub extlink {
 1399:     my ($res,$exact)=@_;
 1400:     if (!$exact) {
 1401: 	$res=&Apache::lonnet::hreflocation($Apache::lonxml::pwd[-1],$res);
 1402:     }
 1403:     push(@Apache::lonxml::extlinks,$res)	 
 1404: }
 1405: 
 1406: sub writeallows {
 1407:     unless ($#extlinks>=0) { return; }
 1408:     my $thisurl = &Apache::lonnet::clutter(shift);
 1409:     if ($env{'httpref.'.$thisurl}) {
 1410: 	$thisurl=$env{'httpref.'.$thisurl};
 1411:     }
 1412:     my $thisdir=$thisurl;
 1413:     $thisdir=~s/\/[^\/]+$//;
 1414:     my %httpref=();
 1415:     foreach (@extlinks) {
 1416:        $httpref{'httpref.'.
 1417:  	        &Apache::lonnet::hreflocation($thisdir,&unescape($_))}=$thisurl;
 1418:     }
 1419:     @extlinks=();
 1420:     &Apache::lonnet::appenv(\%httpref);
 1421: }
 1422: 
 1423: sub register_ssi {
 1424:     my ($url,%form)=@_;
 1425:     push (@Apache::lonxml::ssi_info,{'url'=>$url,'form'=>\%form});
 1426:     return '';
 1427: }
 1428: 
 1429: sub do_registered_ssi {
 1430:     foreach my $info (@Apache::lonxml::ssi_info) {
 1431: 	my %form=%{ $info->{'form'}};
 1432: 	my $url=$info->{'url'};
 1433: 	&Apache::lonnet::ssi($url,%form);
 1434:     }
 1435: }
 1436: 
 1437: sub add_script_result {
 1438:     my ($display) = @_;
 1439:     push(@script_var_displays, $display);
 1440: }
 1441: 
 1442: #
 1443: # Afterburner handles anchors, highlights and links
 1444: #
 1445: sub afterburn {
 1446:     my $result=shift;
 1447:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 1448: 					    ['highlight','anchor','link']);
 1449:     if ($env{'form.highlight'}) {
 1450:        foreach (split(/\,/,$env{'form.highlight'})) {
 1451:            my $anchorname=$_;
 1452: 	   my $matchthis=$anchorname;
 1453:            $matchthis=~s/\_+/\\s\+/g;
 1454:            $result=~s/(\Q$matchthis\E)/\<font color=\"red\"\>$1\<\/font\>/gs;
 1455:        }
 1456:     }
 1457:     if ($env{'form.link'}) {
 1458:        foreach (split(/\,/,$env{'form.link'})) {
 1459:            my ($anchorname,$linkurl)=split(/\>/,$_);
 1460: 	   my $matchthis=$anchorname;
 1461:            $matchthis=~s/\_+/\\s\+/g;
 1462:            $result=~s/(\Q$matchthis\E)/\<a href=\"$linkurl\"\>$1\<\/a\>/gs;
 1463:        }
 1464:     }
 1465:     if ($env{'form.anchor'}) {
 1466:         my $anchorname=$env{'form.anchor'};
 1467: 	my $matchthis=$anchorname;
 1468:         $matchthis=~s/\_+/\\s\+/g;
 1469:         $result=~s/(\Q$matchthis\E)/\<a name=\"$anchorname\"\>$1\<\/a\>/s;
 1470:         $result.=(<<"ENDSCRIPT");
 1471: <script type="text/javascript">
 1472:     document.location.hash='$anchorname';
 1473: </script>
 1474: ENDSCRIPT
 1475:     }
 1476:     return $result;
 1477: }
 1478: 
 1479: sub storefile {
 1480:     my ($file,$contents)=@_;
 1481:     &Apache::lonnet::correct_line_ends(\$contents);
 1482:     if (my $fh=Apache::File->new('>'.$file)) {
 1483: 	print $fh $contents;
 1484:         $fh->close();
 1485:         return 1;
 1486:     } else {
 1487: 	&warning(&mt('Unable to save file [_1]','<tt>'.$file.'</tt>'));
 1488: 	return 0;
 1489:     }
 1490: }
 1491: 
 1492: sub createnewhtml {
 1493:     my $title=&mt('Title of document goes here');
 1494:     my $body=&mt('Body of document goes here');
 1495:     my $filecontents=(<<SIMPLECONTENT);
 1496: <html>
 1497: <head>
 1498: <title>$title</title>
 1499: </head>
 1500: <body bgcolor="#FFFFFF">
 1501: $body
 1502: </body>
 1503: </html>
 1504: SIMPLECONTENT
 1505:     return $filecontents;
 1506: }
 1507: 
 1508: sub createnewsty {
 1509:   my $filecontents=(<<SIMPLECONTENT);
 1510: <definetag name="">
 1511:     <render>
 1512:        <web></web>
 1513:        <tex></tex>
 1514:     </render>
 1515: </definetag>
 1516: SIMPLECONTENT
 1517:   return $filecontents;
 1518: }
 1519: 
 1520: sub createnewjs {
 1521:     my $filecontents=(<<SIMPLECONTENT);
 1522: <script type="text/javascript" language="Javascript">
 1523: 
 1524: </script>
 1525: SIMPLECONTENT
 1526:     return $filecontents;
 1527: }
 1528: 
 1529: sub verify_html {
 1530:     my ($filecontents)=@_;
 1531:     my ($is_html,$is_xml);
 1532:     if ($filecontents =~/(?:\<|\&lt\;)\?xml[^\<]*\?(?:\>|\&gt\;)/is) {
 1533:         $is_xml = 1;
 1534:     } elsif ($filecontents =~/(?:\<|\&lt\;)html(?:\s+[^\<]+|\s*)(?:\>|\&gt\;)/is) {
 1535:         $is_html = 1;
 1536:     }
 1537:     unless ($is_xml || $is_html) {
 1538:         return &mt('File does not have [_1] or [_2] starting tag','&lt;html&gt;','&lt;?xml ?&gt;');
 1539:     }
 1540:     if ($is_html) {
 1541:         if ($filecontents!~/(?:\<|\&lt\;)\/html(?:\>|\&gt\;)/is) {
 1542:             return &mt('File does not have [_1] ending tag','&lt;html&gt;');
 1543:         }
 1544:         if ($filecontents!~/(?:\<|\&lt\;)(?:body|frameset)[^\<]*(?:\>|\&gt\;)/is) {
 1545:             return &mt('File does not have [_1] or [_2] starting tag','&lt;body&gt;','&lt;frameset&gt;');
 1546:         }
 1547:         if ($filecontents!~/(?:\<|\&lt\;)\/(?:body|frameset)[^\<]*(?:\>|\&gt\;)/is) {
 1548:             return &mt('File does not have [_1] or [_2] ending tag','&lt;body&gt;','&lt;frameset&gt;');
 1549:         }
 1550:     }
 1551:     return '';
 1552: }
 1553: 
 1554: sub renderingoptions {
 1555:     my %langchoices=('' => '');
 1556:     foreach (&Apache::loncommon::languageids()) {
 1557:         if (&Apache::loncommon::supportedlanguagecode($_)) {
 1558:             $langchoices{&Apache::loncommon::supportedlanguagecode($_)}
 1559:                        = &Apache::loncommon::plainlanguagedescription($_);
 1560:         }
 1561:     }
 1562:     my $output;
 1563:     unless ($env{'form.forceedit'}) {
 1564:        $output .=
 1565:            '<span class="LC_nobreak">'.
 1566:            &mt('Language:').' '.
 1567:            &Apache::loncommon::select_form(
 1568:                $env{'form.languages'},
 1569:                'languages',
 1570:                {&Apache::lonlocal::texthash(%langchoices)}).
 1571:            '</span>';
 1572:     }
 1573:     $output .=
 1574:      ' <span class="LC_nobreak">'.
 1575:        &mt('Math Rendering:').' '.
 1576:        &Apache::loncommon::select_form(
 1577:            $env{'form.texengine'},
 1578:            'texengine',
 1579:            {&Apache::lonlocal::texthash
 1580:                (''        => '',
 1581:                 'tth'     => 'tth (TeX to HTML)',
 1582:                 'jsMath'  => 'jsMath',
 1583:                 'mimetex' => 'mimetex (Convert to Images)')}).
 1584:      '</span>';
 1585:     return $output;
 1586: }
 1587: 
 1588: sub inserteditinfo {
 1589:       my ($filecontents, $filetype, $filename)=@_;
 1590:       $filecontents = &HTML::Entities::encode($filecontents,'<>&"');
 1591:       my $xml_help = '';
 1592:       my $initialize='';
 1593:       my $textarea_id = 'filecont';
 1594:       my $dragmath_button;
 1595:       my ($add_to_onload, $add_to_onresize);
 1596:       $initialize=&Apache::lonhtmlcommon::spellheader();
 1597:       if (($filetype eq 'html') && (&Apache::lonhtmlcommon::htmlareabrowser())) {
 1598:           my $lang = &Apache::lonhtmlcommon::htmlarea_lang();
 1599:           my %textarea_args = (
 1600:                                 fullpage => 'true',
 1601:                                 dragmath => 'math',
 1602:                               );
 1603:           $initialize .= &Apache::lonhtmlcommon::htmlareaselectactive(\%textarea_args);
 1604:       }
 1605:       $initialize .= (<<FULLPAGE);
 1606: <script type="text/javascript">
 1607: // <![CDATA[
 1608:     function initDocument() {
 1609: 	resize_textarea('$textarea_id','LC_aftertextarea');
 1610:     }
 1611: // ]]>
 1612: </script>
 1613: FULLPAGE
 1614:       if ($filetype eq 'html') {
 1615:           $dragmath_button = '<span id="math_filecont">'.&Apache::lonhtmlcommon::dragmath_button('filecont',1).'</span>';
 1616:           $initialize .= "\n".&Apache::lonhtmlcommon::dragmath_js('EditMathPopup');
 1617:       }
 1618:       $add_to_onload = 'initDocument();';
 1619:       $add_to_onresize = "resize_textarea('$textarea_id','LC_aftertextarea');";
 1620: 
 1621:       if ($filetype eq 'html') {
 1622: 	  $xml_help=&Apache::loncommon::helpLatexCheatsheet();
 1623:       }
 1624: 
 1625:       my $titledisplay=&display_title();
 1626:       my $textareaclass;
 1627:       my %lt=&Apache::lonlocal::texthash('st' => 'Save and Edit',
 1628: 					 'vi' => 'Save and View',
 1629: 					 'dv' => 'Discard Edits and View',
 1630: 					 'un' => 'undo',
 1631: 					 'ed' => 'Edit');
 1632:       my $spelllink = &Apache::lonhtmlcommon::spelllink('xmledit','filecont');
 1633:       my $textarea_events = &Apache::edit::element_change_detection();
 1634:       my $form_events     = &Apache::edit::form_change_detection();
 1635:       my $htmlerror;
 1636:       if ($filetype eq 'html') {
 1637:           $htmlerror=&verify_html($filecontents);
 1638:           if ($htmlerror) {
 1639:               $htmlerror='<span class="LC_error">'.$htmlerror.'</span>';
 1640:           }
 1641:           if (&Apache::lonhtmlcommon::htmlareabrowser()) {
 1642:               $textareaclass = 'class="LC_richDefaultOff"';
 1643:           }
 1644:       }
 1645:       my $editfooter=(<<ENDFOOTER);
 1646: $initialize
 1647: <a name="editsection" />
 1648: <form $form_events method="post" name="xmledit">
 1649:   <div class="LC_edit_problem_editxml_header">
 1650:     <table class="LC_edit_problem_header_title"><tr><td>
 1651:         $filename
 1652:       </td><td align="right">
 1653:         $xml_help
 1654:       </td></tr>
 1655:     </table>
 1656:     <div class="LC_edit_problem_discards">
 1657:       <input type="submit" name="discardview" accesskey="d" value="$lt{'dv'}" />
 1658:       <input type="submit" name="Undo" accesskey="u" value="$lt{'un'}" />
 1659:       $htmlerror $dragmath_button
 1660:     </div>
 1661:     <div class="LC_edit_problem_saves">
 1662:       <input type="submit" name="savethisfile" accesskey="s" value="$lt{'st'}" />
 1663:       <input type="submit" name="viewmode" accesskey="v" value="$lt{'vi'}" />
 1664:     </div>
 1665:   </div>
 1666:   <textarea $textarea_events style="width:100%" cols="80" rows="44" name="filecont" id="filecont" $textareaclass>$filecontents</textarea><br />$spelllink
 1667:   <div id="LC_aftertextarea">
 1668:     <br />
 1669:     $titledisplay
 1670:   </div>
 1671: </form>
 1672: </body>
 1673: ENDFOOTER
 1674:       return ($editfooter,$add_to_onload,$add_to_onresize);;
 1675: }
 1676: 
 1677: sub get_target {
 1678:   my $viewgrades=&Apache::lonnet::allowed('vgr',$env{'request.course.id'});
 1679:   if ( $env{'request.state'} eq 'published') {
 1680:     if ( defined($env{'form.grade_target'})
 1681: 	 && ($viewgrades == 'F' )) {
 1682:       return ($env{'form.grade_target'});
 1683:     } elsif (defined($env{'form.grade_target'})) {
 1684:       if (($env{'form.grade_target'} eq 'web') ||
 1685: 	  ($env{'form.grade_target'} eq 'tex') ) {
 1686: 	return $env{'form.grade_target'}
 1687:       } else {
 1688: 	return 'web';
 1689:       }
 1690:     } else {
 1691:       return 'web';
 1692:     }
 1693:   } elsif ($env{'request.state'} eq 'construct') {
 1694:     if ( defined($env{'form.grade_target'})) {
 1695:       return ($env{'form.grade_target'});
 1696:     } else {
 1697:       return 'web';
 1698:     }
 1699:   } else {
 1700:     return 'web';
 1701:   }
 1702: }
 1703: 
 1704: sub handler {
 1705:     my $request=shift;
 1706: 
 1707:     my $target=&get_target();
 1708:     $Apache::lonxml::debug=$env{'user.debug'};
 1709:     
 1710:     &Apache::loncommon::content_type($request,'text/html');
 1711:     &Apache::loncommon::no_cache($request);
 1712:     if ($env{'request.state'} eq 'published') {
 1713: 	$request->set_last_modified(&Apache::lonnet::metadata($request->uri,
 1714: 							      'lastrevisiondate'));
 1715:     }
 1716:     # Embedded Flash movies from Camtasia served from https will not display in IE
 1717:     #   if XML config file has expired from cache.    
 1718:     if ($ENV{'SERVER_PORT'} == 443) {
 1719:         if ($request->uri =~ /\.xml$/) {
 1720:             my ($httpbrowser,$clientbrowser) =
 1721:                 &Apache::loncommon::decode_user_agent($request);
 1722:             if ($clientbrowser =~ /^explorer$/i) {
 1723:                 delete $request->headers_out->{'Cache-control'};
 1724:                 delete $request->headers_out->{'Pragma'};
 1725:                 my $expiration = time + 60;
 1726:                 my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime($expiration));
 1727:                 $request->headers_out->set("Expires" => $date);
 1728:             }
 1729:         }
 1730:     }
 1731:     $request->send_http_header;
 1732:     
 1733:     return OK if $request->header_only;
 1734: 
 1735: 
 1736:     my $file=&Apache::lonnet::filelocation("",$request->uri);
 1737:     my ($filetype,$breadcrumbtext);
 1738:     if ($file =~ /\.(sty|css|js|txt|tex)$/) {
 1739: 	$filetype=$1;
 1740:     } else {
 1741: 	$filetype='html';
 1742:     }
 1743:     if ($filetype eq 'sty') {
 1744:         $breadcrumbtext = 'Style File Editor';
 1745:     } elsif ($filetype eq 'js') {
 1746:         $breadcrumbtext = 'Javascript Editor';
 1747:     } elsif ($filetype eq 'css') {
 1748:         $breadcrumbtext = 'CSS Editor';
 1749:     } elsif ($filetype eq 'txt') {
 1750:         $breadcrumbtext = 'Text Editor';
 1751:     } elsif ($filetype eq 'tex') {
 1752:         $breadcrumbtext = 'TeX Editor';
 1753:     } else {
 1754:         $breadcrumbtext = 'HTML Editor';
 1755:     }
 1756: 
 1757: #
 1758: # Edit action? Save file.
 1759: #
 1760:     if (!($env{'request.state'} eq 'published')) {
 1761: 	if ($env{'form.savethisfile'} || $env{'form.viewmode'} || $env{'form.Undo'}) {
 1762: 	    my $html_file=&Apache::lonnet::getfile($file);
 1763: 	    my $error = &Apache::lonhomework::handle_save_or_undo($request, \$html_file, \$env{'form.filecont'});
 1764:             if ($env{'form.savethisfile'}) {
 1765:                 $env{'form.editmode'}='Edit'; #force edit mode
 1766:             }
 1767: 	}
 1768:     }
 1769:     my %mystyle;
 1770:     my $result = '';
 1771:     my $filecontents=&Apache::lonnet::getfile($file);
 1772:     if ($filecontents eq -1) {
 1773: 	my $start_page=&Apache::loncommon::start_page('File Error');
 1774: 	my $end_page=&Apache::loncommon::end_page();
 1775:         my $errormsg='<p class="LC_error">'
 1776:                     .&mt('File not found: [_1]'
 1777:                         ,'<span class="LC_filename">'.$file.'</span>')
 1778:                     .'</p>';
 1779: 	$result=(<<ENDNOTFOUND);
 1780: $start_page
 1781: $errormsg
 1782: $end_page
 1783: ENDNOTFOUND
 1784:         $filecontents='';
 1785: 	if ($env{'request.state'} ne 'published') {
 1786: 	    if ($filetype eq 'sty') {
 1787: 		$filecontents=&createnewsty();
 1788:             } elsif ($filetype eq 'js') {
 1789:                 $filecontents=&createnewjs();
 1790:             } elsif ($filetype ne 'css' && $filetype ne 'txt' && $filetype ne 'tex') {
 1791: 		$filecontents=&createnewhtml();
 1792: 	    }
 1793: 	    $env{'form.editmode'}='Edit'; #force edit mode
 1794: 	}
 1795:     } else {
 1796: 	unless ($env{'request.state'} eq 'published') {
 1797: 	    if ($filecontents=~/BEGIN LON-CAPA Internal/) {
 1798: 		&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.'));
 1799: 	    }
 1800: #
 1801: # we are in construction space, see if edit mode forced
 1802:             &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 1803: 						    ['editmode']);
 1804: 	}
 1805: 	if (!$env{'form.editmode'} || $env{'form.viewmode'} || $env{'form.discardview'}) {
 1806:             if ($filetype eq 'html' || $filetype eq 'sty') {
 1807: 	        &Apache::structuretags::reset_problem_globals();
 1808: 	        $result = &Apache::lonxml::xmlparse($request,$target,
 1809:                                                     $filecontents,'',%mystyle);
 1810: 	    # .html files may contain <problem> or <Task> need to clean
 1811: 	    # up if it did
 1812: 	        &Apache::structuretags::reset_problem_globals();
 1813: 	        &Apache::lonhomework::finished_parsing();
 1814:             } elsif ($filetype eq 'tex') {
 1815:                 $result = &Apache::lontexconvert::converted(\$filecontents,
 1816:                               $env{'form.texengine'});
 1817:                 if ($env{'form.return_only_error_and_warning_counts'}) {
 1818:                     $result = "$errorcount:$warningcount";
 1819:                 }
 1820:             } else {
 1821:                 $result = $filecontents;
 1822:             }
 1823: 	    &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 1824: 						    ['rawmode']);
 1825: 	    if ($env{'form.rawmode'}) { $result = $filecontents; }
 1826:             if (($filetype ne 'html') && 
 1827:                 (!$env{'form.return_only_error_and_warning_counts'})) {
 1828:                 my $nochgview = 1;
 1829:                 my $controls = '';
 1830:                     if ($env{'request.state'} eq 'construct') {
 1831:                         $controls = &Apache::loncommon::head_subbox(
 1832:                                         &Apache::loncommon::CSTR_pageheader()
 1833:                                        .&Apache::londefdef::edit_controls($nochgview));
 1834:                     }
 1835:                 if ($filetype ne 'sty' && $filetype ne 'tex') {
 1836:                     $result =~ s/</&lt;/g;
 1837:                     $result =~ s/>/&gt;/g;
 1838:                     $result = '<table class="LC_sty_begin">'.
 1839:                               '<tr><td><b><pre>'.$result.
 1840:                               '</pre></b></td></tr></table>';
 1841:                 }
 1842:                 if ($env{'environment.remote'} eq 'off') {
 1843:                     my $brcrum;
 1844:                     if ($env{'request.state'} eq 'construct') {
 1845:                         $brcrum = [{'href' => &Apache::loncommon::authorspace(),
 1846:                                     'text' => 'Construction Space'},
 1847:                                    {'href' => '',
 1848:                                     'text' => $breadcrumbtext}];
 1849:                     } else {
 1850:                         $brcrum = ''; # FIXME: Where are we?
 1851:                     }
 1852:                     my %options = ('bread_crumbs' => $brcrum,
 1853:                                    'bgcolor'      => '#FFFFFF');
 1854:                     $result =
 1855:                         &Apache::loncommon::start_page(undef,undef,\%options)
 1856:                        .$controls
 1857:                        .$result
 1858:                        .&Apache::loncommon::end_page();
 1859:                 } else {
 1860:                     $result = $controls.$result;
 1861:                 }
 1862:             }
 1863:         }
 1864:     }
 1865: 
 1866: #
 1867: # Edit action? Insert editing commands
 1868: #
 1869:     unless ($env{'request.state'} eq 'published') {
 1870: 	if ($env{'form.editmode'} && (!($env{'form.viewmode'})) && (!($env{'form.discardview'})))
 1871: 	{
 1872: 	    my $displayfile=$request->uri;
 1873: 	    $displayfile=~s/^\/[^\/]*//;
 1874: 
 1875: 	    my ($edit_info, $add_to_onload, $add_to_onresize)=
 1876: 		&inserteditinfo($filecontents,$filetype,$displayfile);
 1877: 
 1878: 	    my %options = 
 1879: 		('add_entries' =>
 1880:                    {'onresize'     => $add_to_onresize,
 1881:                     'onload'       => $add_to_onload,   });
 1882:             my $header;
 1883:             if ($env{'request.state'} eq 'construct') {
 1884:                 $options{'bread_crumbs'} = [{
 1885:                             'href' => &Apache::loncommon::authorspace(),
 1886:                             'text' => 'Construction Space'},
 1887:                            {'href' => '',
 1888:                             'text' => $breadcrumbtext}];
 1889:                 $header = &Apache::loncommon::head_subbox(
 1890:                               &Apache::loncommon::CSTR_pageheader());
 1891:             }
 1892: 	    if ($env{'environment.remote'} ne 'off') {
 1893: 		$options{'bgcolor'}   = '#FFFFFF';
 1894: 		$options{'only_body'} = 1;
 1895: 	    }
 1896: 	    my $js =
 1897: 		&Apache::edit::js_change_detection().
 1898: 		&Apache::loncommon::resize_textarea_js();
 1899: 	    my $start_page = &Apache::loncommon::start_page(undef,$js,
 1900: 							    \%options);
 1901:             $result = $start_page
 1902:                      .$header
 1903:                      .&Apache::lonxml::message_location()
 1904:                      .$edit_info
 1905:                      .&Apache::loncommon::end_page();
 1906:         }
 1907:     }
 1908:     if ($filetype eq 'html') { &writeallows($request->uri); }
 1909: 
 1910:     &Apache::lonxml::add_messages(\$result);
 1911:     $request->print($result);
 1912:     
 1913:     return OK;
 1914: }
 1915: 
 1916: sub display_title {
 1917:     my $result;
 1918:     if ($env{'request.state'} eq 'construct') {
 1919: 	my $title=&Apache::lonnet::gettitle();
 1920: 	if (!defined($title) || $title eq '') {
 1921: 	    $title = $env{'request.filename'};
 1922: 	    $title = substr($title, rindex($title, '/') + 1);
 1923: 	}
 1924:         $result = "<script type='text/javascript'>top.document.title = '$title - LON-CAPA "
 1925:                   .&mt('Construction Space')."';</script>";
 1926:     }
 1927:     return $result;
 1928: }
 1929: 
 1930: sub debug {
 1931:     if ($Apache::lonxml::debug eq "1") {
 1932: 	$|=1;
 1933: 	my $request=$Apache::lonxml::request;
 1934: 	if (!$request) {
 1935: 	    eval { $request=Apache->request; };
 1936: 	}
 1937: 	if (!$request) {
 1938: 	    eval { $request=Apache2::RequestUtil->request; };
 1939: 	}
 1940: 	$request->print('<font size="-2"><pre>DEBUG:'.&HTML::Entities::encode($_[0],'<>&"')."</pre></font>\n");
 1941: 	#&Apache::lonnet::logthis($_[0]);
 1942:     }
 1943: }
 1944: 
 1945: sub show_error_warn_msg {
 1946:     if ($env{'request.filename'} eq '/home/httpd/html/res/lib/templates/simpleproblem.problem' &&
 1947: 	&Apache::lonnet::allowed('mdc',$env{'request.course.id'})) {
 1948: 	return 1;
 1949:     }
 1950:     return (($Apache::lonxml::debug eq 1) ||
 1951: 	    ($env{'request.state'} eq 'construct') ||
 1952: 	    ($Apache::lonhomework::browse eq 'F'
 1953: 	     &&
 1954: 	     $env{'form.show_errors'} eq 'on'));
 1955: }
 1956: 
 1957: sub error {
 1958:     my @errors = @_;
 1959: 
 1960:     $errorcount++;
 1961: 
 1962:     $Apache::lonxml::internal_error=1;
 1963: 
 1964:     if (defined($Apache::inputtags::part)) {
 1965: 	if ( @Apache::inputtags::response ) {
 1966: 	    push(@errors,
 1967: 		 &mt("This error occurred while processing response [_1] in part [_2]",
 1968: 		     $Apache::inputtags::response[-1],
 1969: 		     $Apache::inputtags::part));
 1970: 	} else {
 1971: 	    push(@errors,
 1972: 		 &mt("This error occurred while processing part [_1]",
 1973: 		     $Apache::inputtags::part));
 1974: 	}
 1975:     }
 1976: 
 1977:     if ( &show_error_warn_msg() ) {
 1978: 	# If printing in construction space, put the error inside <pre></pre>
 1979: 	push(@Apache::lonxml::error_messages,
 1980: 	     $Apache::lonxml::warnings_error_header
 1981:              .'<div class="LC_error">'
 1982:              .'<b>'.&mt('ERROR:').' </b>'.join("<br />\n",@errors)
 1983:              ."</div>\n");
 1984: 	$Apache::lonxml::warnings_error_header='';
 1985:     } else {
 1986: 	my $errormsg;
 1987: 	my ($symb)=&Apache::lonnet::symbread();
 1988: 	if ( !$symb ) {
 1989: 	    #public or browsers
 1990: 	    $errormsg=&mt("An error occurred while processing this resource. The author has been notified.");
 1991: 	}
 1992: 	my $host=$Apache::lonnet::perlvar{'lonHostID'};
 1993: 	push(@errors,
 1994:         &mt("The error occurred on host [_1]",
 1995:              "<tt>$host</tt>"));
 1996: 
 1997: 	my $msg = join('<br />', @errors);
 1998: 
 1999: 	#notify author
 2000: 	&Apache::lonmsg::author_res_msg($env{'request.filename'},$msg);
 2001: 	#notify course
 2002: 	if ( $symb && $env{'request.course.id'} ) {
 2003: 	    my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 2004: 	    my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2005: 	    my (undef,%users)=&Apache::lonmsg::decide_receiver(undef,0,1,1,1);
 2006: 	    my $declutter=&Apache::lonnet::declutter($env{'request.filename'});
 2007:             my $baseurl = &Apache::lonnet::clutter($declutter);
 2008: 	    my @userlist;
 2009: 	    foreach (keys %users) {
 2010: 		my ($user,$domain) = split(/:/, $_);
 2011: 		push(@userlist,"$user\@$domain");
 2012: 		my $key=$declutter.'_'.$user.'_'.$domain;
 2013: 		my %lastnotified=&Apache::lonnet::get('nohist_xmlerrornotifications',
 2014: 						      [$key],
 2015: 						      $cdom,$cnum);
 2016: 		my $now=time;
 2017: 		if ($now-$lastnotified{$key}>86400) {
 2018:                     my $title = &Apache::lonnet::gettitle($symb);
 2019:                     my $sentmessage;
 2020: 		    &Apache::lonmsg::user_normal_msg($user,$domain,
 2021: 		        "Error [$title]",$msg,'',$baseurl,'','',
 2022:                         \$sentmessage,$symb,$title,1);
 2023: 		    &Apache::lonnet::put('nohist_xmlerrornotifications',
 2024: 					 {$key => $now},
 2025: 					 $cdom,$cnum);		
 2026: 		}
 2027: 	    }
 2028: 	    if ($env{'request.role.adv'}) {
 2029: 		$errormsg=&mt("An error occurred while processing this resource. The course personnel ([_1]) and the author have been notified.",join(', ',@userlist));
 2030: 	    } else {
 2031: 		$errormsg=&mt("An error occurred while processing this resource. The instructor has been notified.");
 2032: 	    }
 2033: 	}
 2034: 	push(@Apache::lonxml::error_messages,"<b>$errormsg</b> <br />");
 2035:     }
 2036: }
 2037: 
 2038: sub warning {
 2039:     $warningcount++;
 2040:   
 2041:     if ($env{'form.grade_target'} ne 'tex') {
 2042: 	if ( &show_error_warn_msg() ) {
 2043: 	    push(@Apache::lonxml::warning_messages,
 2044: 		 $Apache::lonxml::warnings_error_header
 2045:                 .'<div class="LC_warning">'
 2046:                 .&mt('[_1]W[_2]ARNING','<b>','</b>')."<b>:</b> ".join('<br />',@_)
 2047:                 ."</div>\n"
 2048:                 );
 2049: 	    $Apache::lonxml::warnings_error_header='';
 2050: 	}
 2051:     }
 2052: }
 2053: 
 2054: sub info {
 2055:     if ($env{'form.grade_target'} ne 'tex' 
 2056: 	&& $env{'request.state'} eq 'construct') {
 2057: 	push(@Apache::lonxml::info_messages,join('<br />',@_)."<br />\n");
 2058:     }
 2059: }
 2060: 
 2061: sub message_location {
 2062:     return '__LONCAPA_INTERNAL_MESSAGE_LOCATION__';
 2063: }
 2064: 
 2065: sub add_messages {
 2066:     my ($msg)=@_;
 2067:     my $result=join(' ',
 2068: 		    @Apache::lonxml::info_messages,
 2069: 		    @Apache::lonxml::error_messages,
 2070: 		    @Apache::lonxml::warning_messages);
 2071:     undef(@Apache::lonxml::info_messages);
 2072:     undef(@Apache::lonxml::error_messages);
 2073:     undef(@Apache::lonxml::warning_messages);
 2074:     $$msg=~s/__LONCAPA_INTERNAL_MESSAGE_LOCATION__/$result/;
 2075:     $$msg=~s/__LONCAPA_INTERNAL_MESSAGE_LOCATION__//g;
 2076: }
 2077: 
 2078: sub get_param {
 2079:     my ($param,$parstack,$safeeval,$context,$case_insensitive) = @_;
 2080:     if ( ! $context ) { $context = -1; }
 2081:     my $args ='';
 2082:     if ( $#$parstack > (-2-$context) ) { $args=$$parstack[$context]; }
 2083:     if ( ! $Apache::lonxml::usestyle ) {
 2084: 	$args=$Apache::lonxml::style_values.$args;
 2085:     }
 2086:     if ( ! $args ) { return undef; }
 2087:     if ( $case_insensitive ) {
 2088: 	if ($args =~ s/(my (?:.*))(\$\Q$param\E[,\)])/$1.lc($2)/ei) {
 2089: 	    return &Apache::run::run("{$args;".'return $'.$param.'}',
 2090:                                      $safeeval); #'
 2091: 	} else {
 2092: 	    return undef;
 2093: 	}
 2094:     } else {
 2095: 	if ( $args =~ /my .*\$\Q$param\E[,\)]/ ) {
 2096: 	    return &Apache::run::run("{$args;".'return $'.$param.'}',
 2097:                                      $safeeval); #'
 2098: 	} else {
 2099: 	    return undef;
 2100: 	}
 2101:     }
 2102: }
 2103: 
 2104: sub get_param_var {
 2105:   my ($param,$parstack,$safeeval,$context,$case_insensitive) = @_;
 2106:   if ( ! $context ) { $context = -1; }
 2107:   my $args ='';
 2108:   if ( $#$parstack > (-2-$context) ) { $args=$$parstack[$context]; }
 2109:   if ( ! $Apache::lonxml::usestyle ) {
 2110:       $args=$Apache::lonxml::style_values.$args;
 2111:   }
 2112:   &Apache::lonxml::debug("Args are $args param is $param");
 2113:   if ($case_insensitive) {
 2114:       if (! ($args=~s/(my (?:.*))(\$\Q$param\E[,\)])/$1.lc($2)/ei)) {
 2115: 	  return undef;
 2116:       }
 2117:   } elsif ( $args !~ /my .*\$\Q$param\E[,\)]/ ) { return undef; }
 2118:   my $value=&Apache::run::run("{$args;".'return $'.$param.'}',$safeeval); #'
 2119:   &Apache::lonxml::debug("first run is $value");
 2120:   if ($value =~ /^[\$\@\%][a-zA-Z_]\w*$/) {
 2121:       &Apache::lonxml::debug("doing second");
 2122:       my @result=&Apache::run::run("return $value",$safeeval,1);
 2123:       if (!defined($result[0])) {
 2124: 	  return $value
 2125:       } else {
 2126: 	  if (wantarray) { return @result; } else { return $result[0]; }
 2127:       }
 2128:   } else {
 2129:     return $value;
 2130:   }
 2131: }
 2132: 
 2133: sub register_insert_xml {
 2134:     my $parser = HTML::LCParser->new($Apache::lonnet::perlvar{'lonTabDir'}
 2135: 				     .'/insertlist.xml');
 2136:     my ($tagnum,$in_help)=(0,0);
 2137:     my @alltags;
 2138:     my $tag;
 2139:     while (my $token = $parser->get_token()) {
 2140: 	if ($token->[0] eq 'S') {
 2141: 	    my $key;
 2142: 	    if      ($token->[1] eq 'tag') {
 2143: 		$tag = $token->[2]{'name'};
 2144: 		$insertlist{$tagnum.'.tag'} = $tag;
 2145: 		$insertlist{$tag.'.num'}   = $tagnum;
 2146: 		push(@alltags,$tag);
 2147: 	    } elsif ($in_help && $token->[1] eq 'file') {
 2148: 		$key = $tag.'.helpfile';
 2149: 	    } elsif ($in_help && $token->[1] eq 'description') {
 2150: 		$key = $tag.'.helpdesc';
 2151: 	    } elsif ($token->[1] eq 'description' ||
 2152: 		     $token->[1] eq 'color'       ||
 2153: 		     $token->[1] eq 'show'          ) {
 2154: 		$key = $tag.'.'.$token->[1];
 2155: 	    } elsif ($token->[1] eq 'insert_sub') {
 2156: 		$key = $tag.'.function';
 2157: 	    } elsif ($token->[1] eq 'help') {
 2158: 		$in_help=1;
 2159: 	    } elsif ($token->[1] eq 'allow') {
 2160: 		$key = $tag.'.allow';
 2161: 	    }
 2162: 	    if (defined($key)) {
 2163: 		$insertlist{$key} = $parser->get_text();
 2164: 		$insertlist{$key} =~ s/(^\s*|\s*$ )//gx;
 2165: 	    }
 2166: 	} elsif ($token->[0] eq 'E') {
 2167: 	    if      ($token->[1] eq 'tag') {
 2168: 		undef($tag);
 2169: 		$tagnum++;
 2170: 	    } elsif ($token->[1] eq 'help') {
 2171: 		undef($in_help);
 2172: 	    }
 2173: 	}
 2174:     }
 2175:     
 2176:     # parse the allows and ignore tags set to <show>no</show>
 2177:     foreach my $tag (@alltags) {	
 2178:         next if (!exists($insertlist{$tag.'.allow'}));
 2179: 	my $allow =  $insertlist{$tag.'.allow'};
 2180:        	foreach my $element (split(',',$allow)) {
 2181: 	    $element =~ s/(^\s*|\s*$ )//gx;
 2182: 	    if (!exists($insertlist{$element.'.show'})
 2183:                 || $insertlist{$element.'.show'} ne 'no') {
 2184: 		push(@{ $insertlist{$tag.'.which'} },$element);
 2185: 	    }
 2186: 	}
 2187:     }
 2188: }
 2189: 
 2190: sub register_insert {
 2191:     return &register_insert_xml(@_);
 2192: #    &dump_insertlist('2');
 2193: }
 2194: 
 2195: sub dump_insertlist {
 2196:     my ($ext) = @_;
 2197:     open(XML,">/tmp/insertlist.xml.$ext");
 2198:     print XML ("<insertlist>");
 2199:     my $i=0;
 2200: 
 2201:     while (exists($insertlist{"$i.tag"})) {
 2202: 	my $tag = $insertlist{"$i.tag"};
 2203: 	print XML ("
 2204: \t<tag name=\"$tag\">");
 2205: 	if (defined($insertlist{"$tag.description"})) {
 2206: 	    print XML ("
 2207: \t\t<description>".$insertlist{"$tag.description"}."</description>");
 2208: 	}
 2209: 	if (defined($insertlist{"$tag.color"})) {
 2210: 	    print XML ("
 2211: \t\t<color>".$insertlist{"$tag.color"}."</color>");
 2212: 	}
 2213: 	if (defined($insertlist{"$tag.function"})) {
 2214: 	    print XML ("
 2215: \t\t<insert_sub>".$insertlist{"$tag.function"}."</insert_sub>");
 2216: 	}
 2217: 	if (defined($insertlist{"$tag.show"})
 2218: 	    && $insertlist{"$tag.show"} ne 'yes') {
 2219: 	    print XML ("
 2220: \t\t<show>".$insertlist{"$tag.show"}."</show>");
 2221: 	}
 2222: 	if (defined($insertlist{"$tag.helpfile"})) {
 2223: 	    print XML ("
 2224: \t\t<help>
 2225: \t\t\t<file>".$insertlist{"$tag.helpfile"}."</file>");
 2226: 	    if ($insertlist{"$tag.helpdesc"} ne '') {
 2227: 		print XML ("
 2228: \t\t\t<description>".$insertlist{"$tag.helpdesc"}."</description>");
 2229: 	    }
 2230: 	    print XML ("
 2231: \t\t</help>");
 2232: 	}
 2233: 	if (defined($insertlist{"$tag.which"})) {
 2234: 	    print XML ("
 2235: \t\t<allow>".join(',',sort(@{ $insertlist{"$tag.which"} }))."</allow>");
 2236: 	}
 2237: 	print XML ("
 2238: \t</tag>");
 2239: 	$i++;
 2240:     }
 2241:     print XML ("\n</insertlist>\n");
 2242:     close(XML);
 2243: }
 2244: 
 2245: sub description {
 2246:     my ($token)=@_;
 2247:     my $tag = &get_tag($token);
 2248:     return $insertlist{$tag.'.description'};
 2249: }
 2250: 
 2251: # Returns a list containing the help file, and the description
 2252: sub helpinfo {
 2253:     my ($token)=@_;
 2254:     my $tag = &get_tag($token);
 2255:     return ($insertlist{$tag.'.helpfile'}, $insertlist{$tag.'.helpdesc'});
 2256: }
 2257: 
 2258: sub get_tag {
 2259:     my ($token)=@_;
 2260:     my $tagnum;
 2261:     my $tag=$token->[1];
 2262:     foreach my $namespace (reverse(@Apache::lonxml::namespace)) {
 2263: 	my $testtag = $namespace.'::'.$tag;
 2264: 	$tagnum = $insertlist{"$testtag.num"};
 2265: 	last if (defined($tagnum));
 2266:     }
 2267:     if (!defined($tagnum)) {
 2268: 	$tagnum = $Apache::lonxml::insertlist{"$tag.num"};
 2269:     }
 2270:     return $insertlist{"$tagnum.tag"};
 2271: }
 2272: 
 2273: ############################################################
 2274: #                                           PDF-FORM-METHODS
 2275: 
 2276: =pod
 2277: 
 2278: =item &print_pdf_radiobutton(fieldname, value)
 2279: 
 2280: Returns a latexline to generate a PDF-Form-Radiobutton.
 2281: Note: Radiobuttons with equal names are automaticly grouped
 2282:       in a selection-group.
 2283: 
 2284: $fieldname: PDF internalname of the radiobutton(group)
 2285: $value:     Value of radiobutton
 2286: 
 2287: =cut
 2288: sub print_pdf_radiobutton {
 2289:     my ($fieldname, $value) = @_;
 2290:     return '\radioButton[\symbolchoice{circle}]{'
 2291:            .$fieldname.'}{10bp}{10bp}{'.$value.'}';
 2292: }
 2293: 
 2294: 
 2295: =pod
 2296: 
 2297: =item &print_pdf_start_combobox(fieldname)
 2298: 
 2299: Starts a latexline to generate a PDF-Form-Combobox with text.
 2300: 
 2301: $fieldname: PDF internal name of the Combobox
 2302: 
 2303: =cut
 2304: sub print_pdf_start_combobox {
 2305:     my $result;
 2306:     my ($fieldName) = @_;
 2307:     $result .= '\begin{tabularx}{\textwidth}{p{2.5cm}X}'."\n";
 2308:     $result .= '\comboBox[]{'.$fieldName.'}{2.3cm}{14bp}{'; # 
 2309: 
 2310:     return $result;
 2311: }
 2312: 
 2313: 
 2314: =pod
 2315: 
 2316: =item &print_pdf_add_combobox_option(options)
 2317: 
 2318: Generates a latexline to add Options to a PDF-Form-ComboBox.
 2319: 
 2320: $option: PDF internal name of the Combobox-Option
 2321: 
 2322: =cut
 2323: sub print_pdf_add_combobox_option {
 2324: 
 2325:     my $result;
 2326:     my ($option) = @_;  
 2327: 
 2328:     $result .= '('.$option.')';
 2329:     
 2330:     return $result;
 2331: }
 2332: 
 2333: 
 2334: =pod
 2335: 
 2336: =item &print_pdf_end_combobox(text) {
 2337: 
 2338: Returns latexcode to end a PDF-Form-Combobox with text.
 2339: 
 2340: =cut
 2341: sub print_pdf_end_combobox {
 2342:     my $result;
 2343:     my ($text) = @_;
 2344: 
 2345:     $result .= '}&'.$text."\\\\\n";
 2346:     $result .= '\end{tabularx}' . "\n";
 2347:     $result .= '\hspace{2mm}' . "\n";
 2348:     return $result;
 2349: }
 2350: 
 2351: 
 2352: =pod
 2353: 
 2354: =item &print_pdf_hiddenField(fieldname, user, domain)
 2355: 
 2356: Returns a latexline to generate a PDF-Form-hiddenField with userdata.
 2357: 
 2358: $fieldname label for hiddentextfield
 2359: $user:    name of user
 2360: $domain:  domain of user
 2361: 
 2362: =cut
 2363: sub print_pdf_hiddenfield {
 2364:     my $result;
 2365:     my ($fieldname, $user, $domain) = @_;
 2366: 
 2367:     $result .= '\textField [\F{\FHidden}\F{-\FPrint}\V{'.$domain.'&'.$user.'}]{'.$fieldname.'}{0in}{0in}'."\n";
 2368: 
 2369:     return $result;
 2370: }
 2371: 
 2372: 1;
 2373: __END__
 2374: 

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