File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.548: download - view: text, annotated - select for diffs
Sat Jun 21 23:36:05 2014 UTC (9 years, 11 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Editing HTML file uploaded to Syllabus:
  WYSIWYG editor set to load automatically in this case, so "Edit Math"
  button needs to be hidden by an onload action.

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

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