File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.531.2.16: download - view: text, annotated - select for diffs
Sat Jun 21 23:39:27 2014 UTC (9 years, 10 months ago) by raeburn
Branches: version_2_11_X
CVS tags: version_2_11_0
- For 2.11
  - Backport 1.548.

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

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