File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.577: download - view: text, annotated - select for diffs
Wed Feb 19 23:39:38 2025 UTC (2 days, 9 hours ago) by raeburn
Branches: MAIN
CVS tags: version_2_12_X, HEAD
- WCAG 2 compliance.

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

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