File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.556: download - view: text, annotated - select for diffs
Tue Aug 9 23:43:39 2016 UTC (7 years, 9 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Eliminate "Unescaped left brace in regex is deprecated," warnings
  in error_log with perl 5.22 (Ubuntu 16 LTS).

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

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