File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.528: download - view: text, annotated - select for diffs
Wed Dec 28 13:15:00 2011 UTC (12 years, 6 months ago) by www
Branches: MAIN
CVS tags: HEAD, BZ4492-merge, BZ4492-feature_horizontal_radioresponse
Don't show discussions when previewing a resource that is already in the course

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

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