File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.559: download - view: text, annotated - select for diffs
Sun Nov 12 23:10:33 2017 UTC (6 years, 6 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Use three-argument open() to separate file mode from the filename.

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

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