File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.391: download - view: text, annotated - select for diffs
Tue Dec 6 10:21:18 2005 UTC (18 years, 6 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- reset the counter evertime when looking at resources in CSTR

    1: # The LearningOnline Network with CAPA
    2: # XML Parser Module 
    3: #
    4: # $Id: lonxml.pm,v 1.391 2005/12/06 10:21:18 albertel 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: 
   41: package Apache::lonxml; 
   42: use vars 
   43: qw(@pwd @outputstack $redirection $import @extlinks $metamode $evaluate %insertlist @namespace $errorcount $warningcount @htmlareafields);
   44: use strict;
   45: use HTML::LCParser();
   46: use HTML::TreeBuilder();
   47: use HTML::Entities();
   48: use Safe();
   49: use Safe::Hole();
   50: use Math::Cephes();
   51: use Math::Random();
   52: use Opcode();
   53: use POSIX qw(strftime);
   54: use Time::HiRes qw( gettimeofday tv_interval );
   55: 
   56: sub register {
   57:   my ($space,@taglist) = @_;
   58:   foreach my $temptag (@taglist) {
   59:     push(@{ $Apache::lonxml::alltags{$temptag} },$space);
   60:   }
   61: }
   62: 
   63: sub deregister {
   64:   my ($space,@taglist) = @_;
   65:   foreach my $temptag (@taglist) {
   66:     my $tempspace = $Apache::lonxml::alltags{$temptag}[-1];
   67:     if ($tempspace eq $space) {
   68:       pop(@{ $Apache::lonxml::alltags{$temptag} });
   69:     }
   70:   }
   71:   #&printalltags();
   72: }
   73: 
   74: use Apache::Constants qw(:common);
   75: use Apache::lontexconvert();
   76: use Apache::style();
   77: use Apache::run();
   78: use Apache::londefdef();
   79: use Apache::scripttag();
   80: use Apache::languagetags();
   81: use Apache::edit();
   82: use Apache::inputtags();
   83: use Apache::outputtags();
   84: use Apache::lonnet;
   85: use Apache::File();
   86: use Apache::loncommon();
   87: use Apache::lonfeedback();
   88: use Apache::lonmsg();
   89: use Apache::loncacc();
   90: use Apache::lonlocal;
   91: 
   92: #==================================================   Main subroutine: xmlparse  
   93: #debugging control, to turn on debugging modify the correct handler
   94: $Apache::lonxml::debug=0;
   95: 
   96: # keeps count of the number of warnings and errors generated in a parse
   97: $warningcount=0;
   98: $errorcount=0;
   99: 
  100: #path to the directory containing the file currently being processed
  101: @pwd=();
  102: 
  103: #these two are used for capturing a subset of the output for later processing,
  104: #don't touch them directly use &startredirection and &endredirection
  105: @outputstack = ();
  106: $redirection = 0;
  107: 
  108: #controls wheter the <import> tag actually does
  109: $import = 1;
  110: @extlinks=();
  111: 
  112: # meta mode is a bit weird only some output is to be turned off
  113: #<output> tag turns metamode off (defined in londefdef.pm)
  114: $metamode = 0;
  115: 
  116: # turns on and of run::evaluate actually derefencing var refs
  117: $evaluate = 1;
  118: 
  119: # data structure for eidt mode, determines what tags can go into what other tags
  120: %insertlist=();
  121: 
  122: # stores the list of active tag namespaces
  123: @namespace=();
  124: 
  125: # has the dynamic menu been updated to know about this resource
  126: $Apache::lonxml::registered=0;
  127: 
  128: # a pointer the the Apache request object
  129: $Apache::lonxml::request='';
  130: 
  131: # a problem number counter, and check on ether it is used
  132: $Apache::lonxml::counter=1;
  133: $Apache::lonxml::counter_changed=0;
  134: 
  135: #internal check on whether to look at style defs
  136: $Apache::lonxml::usestyle=1;
  137: 
  138: #locations used to store the parameter string for style substitutions
  139: $Apache::lonxml::style_values='';
  140: $Apache::lonxml::style_end_values='';
  141: 
  142: #array of ssi calls that need to occur after we are done parsing
  143: @Apache::lonxml::ssi_info=();
  144: 
  145: #should we do the postag variable interpolation
  146: $Apache::lonxml::post_evaluate=1;
  147: 
  148: #a header message to emit in the case of any generated warning or errors
  149: $Apache::lonxml::warnings_error_header='';
  150: 
  151: sub xmlbegin {
  152:     my ($style)=@_;
  153:     my $output='';
  154:     @htmlareafields=();
  155:     if ($env{'browser.mathml'}) {
  156: 	$output='<?xml version="1.0"?>'
  157:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
  158: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
  159:             
  160: #	    .'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" [<!ENTITY mathns "http://www.w3.org/1998/Math/MathML">] >'
  161: 	    .'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1 plus MathML 2.0 plus SVG 1.1//EN" "http://www.w3.org/2002/04/xhtml-math-svg/xhtml-math-svg.dtd">'
  162:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
  163: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
  164:     } else {
  165: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>';
  166:     }
  167:     if ($style eq 'encode') {
  168: 	$output=&HTML::Entities::encode($output,'<>&"');
  169:     }
  170:     return $output;
  171: }
  172: 
  173: sub xmlend {
  174:     my ($target,$parser)=@_;
  175:     my $mode='xml';
  176:     my $status='OPEN';
  177:     if ($Apache::lonhomework::parsing_a_problem ||
  178: 	$Apache::lonhomework::parsing_a_task ) {
  179: 	$mode='problem';
  180: 	$status=$Apache::inputtags::status[-1]; 
  181:     }
  182:     my $discussion;
  183:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
  184: 					   ['LONCAPA_INTERNAL_no_discussion']);
  185:     if (! exists($env{'form.LONCAPA_INTERNAL_no_discussion'}) ||
  186:         $env{'form.LONCAPA_INTERNAL_no_discussion'} ne 'true') {
  187:         $discussion=&Apache::lonfeedback::list_discussion($mode,$status);
  188:     }
  189:     if ($target eq 'tex') {
  190: 	$discussion.='<tex>\keephidden{ENDOFPROBLEM}\vskip 0.5mm\noindent\makebox[\textwidth/$number_of_columns][b]{\hrulefill}\end{document}</tex>';
  191: 	&Apache::lonxml::newparser($parser,\$discussion,'');
  192: 	return '';
  193:     } else {
  194: 	return $discussion.&Apache::loncommon::endbodytag();
  195:     }
  196: }
  197: 
  198: sub tokeninputfield {
  199:     my $defhost=$Apache::lonnet::perlvar{'lonHostID'};
  200:     $defhost=~tr/a-z/A-Z/;
  201:     return (<<ENDINPUTFIELD)
  202: <script type="text/javascript">
  203:     function updatetoken() {
  204: 	var comp=new Array;
  205:         var barcode=unescape(document.tokeninput.barcode.value);
  206:         comp=barcode.split('*');
  207:         if (typeof(comp[0])!="undefined") {
  208: 	    document.tokeninput.codeone.value=comp[0];
  209: 	}
  210:         if (typeof(comp[1])!="undefined") {
  211: 	    document.tokeninput.codetwo.value=comp[1];
  212: 	}
  213:         if (typeof(comp[2])!="undefined") {
  214:             comp[2]=comp[2].toUpperCase();
  215: 	    document.tokeninput.codethree.value=comp[2];
  216: 	}
  217:         document.tokeninput.barcode.value='';
  218:     }  
  219: </script>
  220: <form method="post" name="tokeninput">
  221: <table border="2" bgcolor="#FFFFBB">
  222: <tr><th>DocID Checkin</th></tr>
  223: <tr><td>
  224: <table>
  225: <tr>
  226: <td>Scan in Barcode</td>
  227: <td><input type="text" size="22" name="barcode" 
  228: onChange="updatetoken()"/></td>
  229: </tr>
  230: <tr><td><i>or</i> Type in DocID</td>
  231: <td>
  232: <input type="text" size="5" name="codeone" />
  233: <b><font size="+2">*</font></b>
  234: <input type="text" size="5" name="codetwo" />
  235: <b><font size="+2">*</font></b>
  236: <input type="text" size="10" name="codethree" value="$defhost" 
  237: onChange="this.value=this.value.toUpperCase()" />
  238: </td></tr>
  239: </table>
  240: </td></tr>
  241: <tr><td><input type="submit" value="Check in DocID" /></td></tr>
  242: </table>
  243: </form>
  244: ENDINPUTFIELD
  245: }
  246: 
  247: sub maketoken {
  248:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
  249:     unless ($symb) {
  250: 	$symb=&Apache::lonnet::symbread();
  251:     }
  252:     unless ($tuname) {
  253: 	$tuname=$env{'user.name'};
  254:         $tudom=$env{'user.domain'};
  255:         $tcrsid=$env{'request.course.id'};
  256:     }
  257: 
  258:     return &Apache::lonnet::checkout($symb,$tuname,$tudom,$tcrsid);
  259: }
  260: 
  261: sub printtokenheader {
  262:     my ($target,$token,$tsymb,$tcrsid,$tudom,$tuname)=@_;
  263:     unless ($token) { return ''; }
  264: 
  265:     my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
  266:     unless ($tsymb) {
  267: 	$tsymb=$symb;
  268:     }
  269:     unless ($tuname) {
  270: 	$tuname=$name;
  271:         $tudom=$domain;
  272:         $tcrsid=$courseid;
  273:     }
  274: 
  275:     my $plainname=&Apache::loncommon::plainname($tuname,$tudom);
  276: 
  277:     if ($target eq 'web') {
  278:         my %idhash=&Apache::lonnet::idrget($tudom,($tuname));
  279: 	return 
  280:  '<img align="right" src="/cgi-bin/barcode.png?encode='.$token.'" />'.
  281:                &mt('Checked out for').' '.$plainname.
  282:                '<br />'.&mt('User').': '.$tuname.' at '.$tudom.
  283: 	       '<br />'.&mt('ID').': '.$idhash{$tuname}.
  284: 	       '<br />'.&mt('CourseID').': '.$tcrsid.
  285: 	       '<br />'.&mt('Course').': '.$env{'course.'.$tcrsid.'.description'}.
  286:                '<br />'.&mt('DocID').': '.$token.
  287:                '<br />'.&mt('Time').': '.&Apache::lonlocal::locallocaltime().'<hr />';
  288:     } else {
  289:         return $token;
  290:     }
  291: }
  292: 
  293: sub fontsettings {
  294:     my $headerstring='';
  295:     if (($env{'browser.os'} eq 'mac') && (!$env{'browser.mathml'})) { 
  296: 	$headerstring.=
  297: 	    '<meta Content-Type="text/html; charset=x-mac-roman" />';
  298:     } elsif (!$env{'browser.mathml'} && $env{'browser.unicode'}) {
  299: 	$headerstring.=
  300: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
  301:     }
  302:     return $headerstring;
  303: }
  304: 
  305: sub printalltags {
  306:   my $temp;
  307:   foreach $temp (sort keys %Apache::lonxml::alltags) {
  308:     &Apache::lonxml::debug("$temp -- ".
  309: 		  join(',',@{ $Apache::lonxml::alltags{$temp} }));
  310:   }
  311: }
  312: 
  313: sub xmlparse {
  314:  my ($request,$target,$content_file_string,$safeinit,%style_for_target) = @_;
  315: 
  316:  &setup_globals($request,$target);
  317:  &Apache::inputtags::initialize_inputtags();
  318:  &Apache::bridgetask::initialize_bridgetask();
  319:  &Apache::outputtags::initialize_outputtags();
  320:  &Apache::edit::initialize_edit();
  321:  &Apache::londefdef::initialize_londefdef();
  322: 
  323: #
  324: # do we have a course style file?
  325: #
  326: 
  327:  if ($env{'request.course.id'} && $env{'request.state'} ne 'construct') {
  328:      my $bodytext=
  329: 	 $env{'course.'.$env{'request.course.id'}.'.default_xml_style'};
  330:      if ($bodytext) {
  331: 	 foreach my $file (split(',',$bodytext)) {
  332: 	     my $location=&Apache::lonnet::filelocation('',$file);
  333: 	     my $styletext=&Apache::lonnet::getfile($location);
  334: 	     if ($styletext ne '-1') {
  335: 		 %style_for_target = (%style_for_target,
  336: 				      &Apache::style::styleparser($target,$styletext));
  337: 	     }
  338: 	 }
  339:      }
  340:  } elsif ($env{'construct.style'} && ($env{'request.state'} eq 'construct')) {
  341:      my $location=&Apache::lonnet::filelocation('',$env{'construct.style'});
  342:      my $styletext=&Apache::lonnet::getfile($location);
  343:        if ($styletext ne '-1') {
  344:           %style_for_target = (%style_for_target,
  345:                           &Apache::style::styleparser($target,$styletext));
  346:       }
  347:  }
  348: #&printalltags();
  349:  my @pars = ();
  350:  my $pwd=$env{'request.filename'};
  351:  $pwd =~ s:/[^/]*$::;
  352:  &newparser(\@pars,\$content_file_string,$pwd);
  353: 
  354:  my $safeeval = new Safe;
  355:  my $safehole = new Safe::Hole;
  356:  &init_safespace($target,$safeeval,$safehole,$safeinit);
  357: #-------------------- Redefinition of the target in the case of compound target
  358: 
  359:  ($target, my @tenta) = split('&&',$target);
  360: 
  361:  my @stack = ();
  362:  my @parstack = ();
  363:  &initdepth();
  364:  &init_alarm();
  365:  my $finaloutput = &inner_xmlparse($target,\@stack,\@parstack,\@pars,
  366: 				   $safeeval,\%style_for_target);
  367: 
  368:  if ($env{'request.uri'}) {
  369:     &writeallows($env{'request.uri'});
  370:  }
  371:  &do_registered_ssi();
  372:  if ($Apache::lonxml::counter_changed) { &store_counter() }
  373:  if ($env{'form.return_only_error_and_warning_counts'}) {
  374:      return "$errorcount:$warningcount";
  375:  }
  376:  return $finaloutput;
  377: }
  378: 
  379: sub latex_special_symbols {
  380:     my ($string,$where)=@_;
  381:     if ($where eq 'header') {
  382: 	$string =~ s/(\\|_|\^)/ /g;
  383: 	$string =~ s/(\$|%|\{|\})/\\$1/g;
  384: 	$string =~ s/_/ /g;
  385: 	$string=&Apache::lonprintout::character_chart($string);
  386: 	# any & or # leftover should be safe to just escape
  387:         $string=~s/([^\\])\&/$1\\\&/g;
  388:         $string=~s/([^\\])\#/$1\\\#/g;
  389:     } else {
  390: 	$string=~s/\\/\\ensuremath{\\backslash}/g;
  391: 	$string=~s/\\\%|\%/\\\%/g;
  392: 	$string=~s/\\{|{/\\{/g;
  393: 	$string=~s/\\}|}/\\}/g;
  394: 	$string=~s/\\ensuremath\\{\\backslash\\}/\\ensuremath{\\backslash}/g;
  395: 	$string=~s/\\\$|\$/\\\$/g;
  396: 	$string=~s/\\\_|\_/\\\_/g;
  397:         $string=~s/([^\\]|^)(\~|\^)/$1\\$2\\strut /g;
  398: 	$string=~s/(>|<)/\\ensuremath\{$1\}/g; #more or less
  399: 	$string=&Apache::lonprintout::character_chart($string);
  400: 	# any & or # leftover should be safe to just escape
  401: 	$string=~s/\\\&|\&/\\\&/g;
  402: 	$string=~s/\\\#|\#/\\\#/g;
  403:         $string=~s/\|/\$\\mid\$/g;
  404: #single { or } How to escape?
  405:     }
  406:     return $string;
  407: }
  408: 
  409: sub inner_xmlparse {
  410:   my ($target,$stack,$parstack,$pars,$safeeval,$style_for_target)=@_;
  411:   my $finaloutput = '';
  412:   my $result;
  413:   my $token;
  414:   my $dontpop=0;
  415:   my $startredirection = $Apache::lonxml::redirection;
  416:   while ( $#$pars > -1 ) {
  417:     while ($token = $$pars['-1']->get_token) {
  418:       if (($token->[0] eq 'T') || ($token->[0] eq 'C') ) {
  419: 	if ($metamode<1) {
  420: 	    my $text=$token->[1];
  421: 	    if ($token->[0] eq 'C' && $target eq 'tex') {
  422: 		$text = '';
  423: #		$text = '%'.$text."\n";
  424: 	    }
  425: 	    $result.=$text;
  426: 	}
  427:       } elsif (($token->[0] eq 'D')) {
  428: 	if ($metamode<1 && $target eq 'web') {
  429: 	    my $text=$token->[1];
  430: 	    $result.=$text;
  431: 	}
  432:       } elsif ($token->[0] eq 'PI') {
  433: 	if ($metamode<1 && $target eq 'web') {
  434: 	  $result=$token->[2];
  435: 	}
  436:       } elsif ($token->[0] eq 'S') {
  437: 	# add tag to stack
  438: 	push (@$stack,$token->[1]);
  439: 	# add parameters list to another stack
  440: 	push (@$parstack,&parstring($token));
  441: 	&increasedepth($token);
  442: 	if ($Apache::lonxml::usestyle &&
  443: 	    exists($$style_for_target{$token->[1]})) {
  444: 	    $Apache::lonxml::usestyle=0;
  445: 	    my $string=$$style_for_target{$token->[1]}.
  446: 	      '<LONCAPA_INTERNAL_TURN_STYLE_ON />';
  447: 	    &Apache::lonxml::newparser($pars,\$string);
  448: 	    $Apache::lonxml::style_values=$$parstack[-1];
  449: 	    $Apache::lonxml::style_end_values=$$parstack[-1];
  450: 	} else {
  451: 	  $result = &callsub("start_$token->[1]", $target, $token, $stack,
  452: 			     $parstack, $pars, $safeeval, $style_for_target);
  453: 	}
  454:       } elsif ($token->[0] eq 'E') {
  455: 	if ($Apache::lonxml::usestyle &&
  456: 	    exists($$style_for_target{'/'."$token->[1]"})) {
  457: 	    $Apache::lonxml::usestyle=0;
  458: 	    my $string=$$style_for_target{'/'.$token->[1]}.
  459: 	      '<LONCAPA_INTERNAL_TURN_STYLE_ON end="'.$token->[1].'" />';
  460: 	    &Apache::lonxml::newparser($pars,\$string);
  461: 	    $Apache::lonxml::style_values=$Apache::lonxml::style_end_values;
  462: 	    $Apache::lonxml::style_end_values='';
  463: 	    $dontpop=1;
  464: 	} else {
  465: 	    #clear out any tags that didn't end
  466: 	    while ($token->[1] ne $$stack['-1'] && ($#$stack > -1)) {
  467: 		my $lasttag=$$stack[-1];
  468: 		if ($token->[1] =~ /^\Q$lasttag\E$/i) {
  469: 		    &Apache::lonxml::warning('Using tag &lt;/'.$token->[1].'&gt; on line '.$token->[3].' as end tag to &lt;'.$$stack[-1].'&gt;');
  470: 		    last;
  471: 		} else {
  472: 		    &Apache::lonxml::warning('Found tag &lt;/'.$token->[1].'&gt; on line '.$token->[3].' when looking for &lt;/'.$$stack[-1].'&gt; in file');
  473: 		    &end_tag($stack,$parstack,$token);
  474: 		}
  475: 	    }
  476: 	    $result = &callsub("end_$token->[1]", $target, $token, $stack,
  477: 			       $parstack, $pars,$safeeval, $style_for_target);
  478: 	}
  479:       } else {
  480: 	&Apache::lonxml::error("Unknown token event :$token->[0]:$token->[1]:");
  481:       }
  482:       #evaluate variable refs in result
  483:       if ($Apache::lonxml::post_evaluate &&$result ne "") {
  484: 	  my $extras;
  485: 	  if (!$Apache::lonxml::usestyle) {
  486: 	      $extras=$Apache::lonxml::style_values;
  487: 	  }
  488: 	if ( $#$parstack > -1 ) {
  489: 	  $result=&Apache::run::evaluate($result,$safeeval,$extras.$$parstack[-1]);
  490: 	} else {
  491: 	  $result= &Apache::run::evaluate($result,$safeeval,$extras);
  492: 	}
  493:       }
  494:       $Apache::lonxml::post_evaluate=1;
  495: 
  496:       if (($token->[0] eq 'T') || ($token->[0] eq 'C') || ($token->[0] eq 'D') ) {
  497: 	  #Style file definitions should be correct
  498: 	  if ($target eq 'tex' && ($Apache::lonxml::usestyle)) {
  499: 	      $result=&latex_special_symbols($result);
  500: 	  }
  501:       }
  502: 
  503:       if ($Apache::lonxml::redirection) {
  504: 	$Apache::lonxml::outputstack['-1'] .= $result;
  505:       } else {
  506: 	$finaloutput.=$result;
  507:       }
  508:       $result = '';
  509: 
  510:       if ($token->[0] eq 'E' && !$dontpop) {
  511: 	&end_tag($stack,$parstack,$token);
  512:       }
  513:       $dontpop=0;
  514:     }	
  515:     if ($#$pars > -1) {
  516: 	pop @$pars;
  517: 	pop @Apache::lonxml::pwd;
  518:     }
  519:   }
  520: 
  521:   # if ($target eq 'meta') {
  522:   #   $finaloutput.=&endredirection;
  523:   # }
  524: 
  525:   if ($target eq 'grade') { &endredirection(); }
  526:   if ( $Apache::lonxml::redirection > $startredirection) {
  527:       while ($Apache::lonxml::redirection > $startredirection) {
  528: 	  $finaloutput .= &endredirection();
  529:       }
  530:   }
  531:   if (($ENV{'QUERY_STRING'}) && ($target eq 'web')) {
  532:     $finaloutput=&afterburn($finaloutput);
  533:   }	    
  534:   return $finaloutput;
  535: }
  536: 
  537: ## 
  538: ## Looks to see if there is a subroutine defined for this tag.  If so, call it,
  539: ## otherwise do not call it as we do not know what it is.
  540: ##
  541: sub callsub {
  542:   my ($sub,$target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  543:   my $currentstring='';
  544:   my $nodefault;
  545:   {
  546:     my $sub1;
  547:     no strict 'refs';
  548:     my $tag=$token->[1];
  549: # get utterly rid of extended html tags
  550:     if ($tag=~/^x\-/i) { return ''; }
  551:     my $space=$Apache::lonxml::alltags{$tag}[-1];
  552:     if (!$space) {
  553:      	$tag=~tr/A-Z/a-z/;
  554: 	$sub=~tr/A-Z/a-z/;
  555: 	$space=$Apache::lonxml::alltags{$tag}[-1]
  556:     }
  557: 
  558:     my $deleted=0;
  559:     $Apache::lonxml::curdepth=join('_',@Apache::lonxml::depthcounter);
  560:     if (($token->[0] eq 'S') && ($target eq 'modified')) {
  561:       $deleted=&Apache::edit::handle_delete($space,$target,$token,$tagstack,
  562: 					     $parstack,$parser,$safeeval,
  563: 					     $style);
  564:     }
  565:     if (!$deleted) {
  566:       if ($space) {
  567: 	#&Apache::lonxml::debug("Calling sub $sub in $space $metamode");
  568: 	$sub1="$space\:\:$sub";
  569: 	($currentstring,$nodefault) = &$sub1($target,$token,$tagstack,
  570: 					     $parstack,$parser,$safeeval,
  571: 					     $style);
  572:       } else {
  573:           if ($target eq 'tex') {
  574:               # throw away tag name
  575:               return '';
  576:           }
  577: 	#&Apache::lonxml::debug("NOT Calling sub $sub in $space $metamode");
  578: 	if ($metamode <1) {
  579: 	  if (defined($token->[4]) && ($metamode < 1)) {
  580: 	    $currentstring = $token->[4];
  581: 	  } else {
  582: 	    $currentstring = $token->[2];
  583: 	  }
  584: 	}
  585:       }
  586:       #    &Apache::lonxml::debug("nodefalt:$nodefault:");
  587:       if ($currentstring eq '' && $nodefault eq '') {
  588: 	if ($target eq 'edit') {
  589: 	  #&Apache::lonxml::debug("doing default edit for $token->[1]");
  590: 	  if ($token->[0] eq 'S') {
  591: 	    $currentstring = &Apache::edit::tag_start($target,$token);
  592: 	  } elsif ($token->[0] eq 'E') {
  593: 	    $currentstring = &Apache::edit::tag_end($target,$token);
  594: 	  }
  595: 	} elsif ($target eq 'modified') {
  596: 	  if ($token->[0] eq 'S') {
  597: 	    $currentstring = $token->[4];
  598: 	    $currentstring.=&Apache::edit::handle_insert();
  599: 	  } elsif ($token->[0] eq 'E') {
  600: 	    $currentstring = $token->[2];
  601:             $currentstring.=&Apache::edit::handle_insertafter($token->[1]);
  602: 	  } else {
  603: 	    $currentstring = $token->[2];
  604: 	  }
  605: 	}
  606:       }
  607:     }
  608:     use strict 'refs';
  609:   }
  610:   return $currentstring;
  611: }
  612: 
  613: sub setup_globals {
  614:   my ($request,$target)=@_;
  615:   $Apache::lonxml::request=$request;
  616:   $Apache::lonxml::registered = 0;
  617:   @Apache::lonxml::htmlareafields=();
  618:   $errorcount=0;
  619:   $warningcount=0;
  620:   $Apache::lonxml::default_homework_loaded=0;
  621:   $Apache::lonxml::usestyle=1;
  622:   &init_counter();
  623:   @Apache::lonxml::pwd=();
  624:   @Apache::lonxml::extlinks=();
  625:   @Apache::lonxml::ssi_info=();
  626:   $Apache::lonxml::post_evaluate=1;
  627:   $Apache::lonxml::warnings_error_header='';
  628:   if ($target eq 'meta') {
  629:     $Apache::lonxml::redirection = 0;
  630:     $Apache::lonxml::metamode = 1;
  631:     $Apache::lonxml::evaluate = 1;
  632:     $Apache::lonxml::import = 0;
  633:   } elsif ($target eq 'answer') {
  634:     $Apache::lonxml::redirection = 0;
  635:     $Apache::lonxml::metamode = 1;
  636:     $Apache::lonxml::evaluate = 1;
  637:     $Apache::lonxml::import = 1;
  638:   } elsif ($target eq 'grade') {
  639:     &startredirection(); #ended in inner_xmlparse on exit
  640:     $Apache::lonxml::metamode = 0;
  641:     $Apache::lonxml::evaluate = 1;
  642:     $Apache::lonxml::import = 1;
  643:   } elsif ($target eq 'modified') {
  644:     $Apache::lonxml::redirection = 0;
  645:     $Apache::lonxml::metamode = 0;
  646:     $Apache::lonxml::evaluate = 0;
  647:     $Apache::lonxml::import = 0;
  648:   } elsif ($target eq 'edit') {
  649:     $Apache::lonxml::redirection = 0;
  650:     $Apache::lonxml::metamode = 0;
  651:     $Apache::lonxml::evaluate = 0;
  652:     $Apache::lonxml::import = 0;
  653:   } elsif ($target eq 'analyze') {
  654:     $Apache::lonxml::redirection = 0;
  655:     $Apache::lonxml::metamode = 0;
  656:     $Apache::lonxml::evaluate = 1;
  657:     $Apache::lonxml::import = 1;
  658:   } else {
  659:     $Apache::lonxml::redirection = 0;
  660:     $Apache::lonxml::metamode = 0;
  661:     $Apache::lonxml::evaluate = 1;
  662:     $Apache::lonxml::import = 1;
  663:   }
  664: }
  665: 
  666: sub init_safespace {
  667:   my ($target,$safeeval,$safehole,$safeinit) = @_;
  668:   $safeeval->deny_only(':dangerous');
  669:   $safeeval->reval('use Math::Complex;');
  670:   $safeeval->permit_only(":default");
  671:   $safeeval->permit("entereval");
  672:   $safeeval->permit(":base_math");
  673:   $safeeval->permit("sort");
  674:   $safeeval->permit("time");
  675:   $safeeval->deny("rand");
  676:   $safeeval->deny("srand");
  677:   $safeeval->deny(":base_io");
  678:   $safehole->wrap(\&Apache::scripttag::xmlparse,$safeeval,'&xmlparse');
  679:   $safehole->wrap(\&Apache::outputtags::multipart,$safeeval,'&multipart');
  680:   $safehole->wrap(\&Apache::lonnet::EXT,$safeeval,'&EXT');
  681:   $safehole->wrap(\&Apache::chemresponse::chem_standard_order,$safeeval,
  682: 		  '&chem_standard_order');
  683:   $safehole->wrap(\&Apache::response::check_status,$safeeval,'&check_status');
  684: 
  685:   $safehole->wrap(\&Math::Cephes::asin,$safeeval,'&asin');
  686:   $safehole->wrap(\&Math::Cephes::acos,$safeeval,'&acos');
  687:   $safehole->wrap(\&Math::Cephes::atan,$safeeval,'&atan');
  688:   $safehole->wrap(\&Math::Cephes::sinh,$safeeval,'&sinh');
  689:   $safehole->wrap(\&Math::Cephes::cosh,$safeeval,'&cosh');
  690:   $safehole->wrap(\&Math::Cephes::tanh,$safeeval,'&tanh');
  691:   $safehole->wrap(\&Math::Cephes::asinh,$safeeval,'&asinh');
  692:   $safehole->wrap(\&Math::Cephes::acosh,$safeeval,'&acosh');
  693:   $safehole->wrap(\&Math::Cephes::atanh,$safeeval,'&atanh');
  694:   $safehole->wrap(\&Math::Cephes::erf,$safeeval,'&erf');
  695:   $safehole->wrap(\&Math::Cephes::erfc,$safeeval,'&erfc');
  696:   $safehole->wrap(\&Math::Cephes::j0,$safeeval,'&j0');
  697:   $safehole->wrap(\&Math::Cephes::j1,$safeeval,'&j1');
  698:   $safehole->wrap(\&Math::Cephes::jn,$safeeval,'&jn');
  699:   $safehole->wrap(\&Math::Cephes::jv,$safeeval,'&jv');
  700:   $safehole->wrap(\&Math::Cephes::y0,$safeeval,'&y0');
  701:   $safehole->wrap(\&Math::Cephes::y1,$safeeval,'&y1');
  702:   $safehole->wrap(\&Math::Cephes::yn,$safeeval,'&yn');
  703:   $safehole->wrap(\&Math::Cephes::yv,$safeeval,'&yv');
  704:   
  705:   $safehole->wrap(\&Math::Cephes::bdtr  ,$safeeval,'&bdtr'  );
  706:   $safehole->wrap(\&Math::Cephes::bdtrc ,$safeeval,'&bdtrc' );
  707:   $safehole->wrap(\&Math::Cephes::bdtri ,$safeeval,'&bdtri' );
  708:   $safehole->wrap(\&Math::Cephes::btdtr ,$safeeval,'&btdtr' );
  709:   $safehole->wrap(\&Math::Cephes::chdtr ,$safeeval,'&chdtr' );
  710:   $safehole->wrap(\&Math::Cephes::chdtrc,$safeeval,'&chdtrc');
  711:   $safehole->wrap(\&Math::Cephes::chdtri,$safeeval,'&chdtri');
  712:   $safehole->wrap(\&Math::Cephes::fdtr  ,$safeeval,'&fdtr'  );
  713:   $safehole->wrap(\&Math::Cephes::fdtrc ,$safeeval,'&fdtrc' );
  714:   $safehole->wrap(\&Math::Cephes::fdtri ,$safeeval,'&fdtri' );
  715:   $safehole->wrap(\&Math::Cephes::gdtr  ,$safeeval,'&gdtr'  );
  716:   $safehole->wrap(\&Math::Cephes::gdtrc ,$safeeval,'&gdtrc' );
  717:   $safehole->wrap(\&Math::Cephes::nbdtr ,$safeeval,'&nbdtr' );
  718:   $safehole->wrap(\&Math::Cephes::nbdtrc,$safeeval,'&nbdtrc');
  719:   $safehole->wrap(\&Math::Cephes::nbdtri,$safeeval,'&nbdtri');
  720:   $safehole->wrap(\&Math::Cephes::ndtr  ,$safeeval,'&ndtr'  );
  721:   $safehole->wrap(\&Math::Cephes::ndtri ,$safeeval,'&ndtri' );
  722:   $safehole->wrap(\&Math::Cephes::pdtr  ,$safeeval,'&pdtr'  );
  723:   $safehole->wrap(\&Math::Cephes::pdtrc ,$safeeval,'&pdtrc' );
  724:   $safehole->wrap(\&Math::Cephes::pdtri ,$safeeval,'&pdtri' );
  725:   $safehole->wrap(\&Math::Cephes::stdtr ,$safeeval,'&stdtr' );
  726:   $safehole->wrap(\&Math::Cephes::stdtri,$safeeval,'&stdtri');
  727: 
  728:   $safehole->wrap(\&Math::Cephes::Matrix::mat,$safeeval,'&mat');
  729:   $safehole->wrap(\&Math::Cephes::Matrix::new,$safeeval,
  730: 		  '&Math::Cephes::Matrix::new');
  731:   $safehole->wrap(\&Math::Cephes::Matrix::coef,$safeeval,
  732: 		  '&Math::Cephes::Matrix::coef');
  733:   $safehole->wrap(\&Math::Cephes::Matrix::clr,$safeeval,
  734: 		  '&Math::Cephes::Matrix::clr');
  735:   $safehole->wrap(\&Math::Cephes::Matrix::add,$safeeval,
  736: 		  '&Math::Cephes::Matrix::add');
  737:   $safehole->wrap(\&Math::Cephes::Matrix::sub,$safeeval,
  738: 		  '&Math::Cephes::Matrix::sub');
  739:   $safehole->wrap(\&Math::Cephes::Matrix::mul,$safeeval,
  740: 		  '&Math::Cephes::Matrix::mul');
  741:   $safehole->wrap(\&Math::Cephes::Matrix::div,$safeeval,
  742: 		  '&Math::Cephes::Matrix::div');
  743:   $safehole->wrap(\&Math::Cephes::Matrix::inv,$safeeval,
  744: 		  '&Math::Cephes::Matrix::inv');
  745:   $safehole->wrap(\&Math::Cephes::Matrix::transp,$safeeval,
  746: 		  '&Math::Cephes::Matrix::transp');
  747:   $safehole->wrap(\&Math::Cephes::Matrix::simq,$safeeval,
  748: 		  '&Math::Cephes::Matrix::simq');
  749:   $safehole->wrap(\&Math::Cephes::Matrix::mat_to_vec,$safeeval,
  750: 		  '&Math::Cephes::Matrix::mat_to_vec');
  751:   $safehole->wrap(\&Math::Cephes::Matrix::vec_to_mat,$safeeval,
  752: 		  '&Math::Cephes::Matrix::vec_to_mat');
  753:   $safehole->wrap(\&Math::Cephes::Matrix::check,$safeeval,
  754: 		  '&Math::Cephes::Matrix::check');
  755:   $safehole->wrap(\&Math::Cephes::Matrix::check,$safeeval,
  756: 		  '&Math::Cephes::Matrix::check');
  757: 
  758: #  $safehole->wrap(\&Math::Cephes::new_fract,$safeeval,'&new_fract');
  759: #  $safehole->wrap(\&Math::Cephes::radd,$safeeval,'&radd');
  760: #  $safehole->wrap(\&Math::Cephes::rsub,$safeeval,'&rsub');
  761: #  $safehole->wrap(\&Math::Cephes::rmul,$safeeval,'&rmul');
  762: #  $safehole->wrap(\&Math::Cephes::rdiv,$safeeval,'&rdiv');
  763: #  $safehole->wrap(\&Math::Cephes::euclid,$safeeval,'&euclid');
  764: 
  765:   $safehole->wrap(\&Math::Random::random_beta,$safeeval,'&math_random_beta');
  766:   $safehole->wrap(\&Math::Random::random_chi_square,$safeeval,'&math_random_chi_square');
  767:   $safehole->wrap(\&Math::Random::random_exponential,$safeeval,'&math_random_exponential');
  768:   $safehole->wrap(\&Math::Random::random_f,$safeeval,'&math_random_f');
  769:   $safehole->wrap(\&Math::Random::random_gamma,$safeeval,'&math_random_gamma');
  770:   $safehole->wrap(\&Math::Random::random_multivariate_normal,$safeeval,'&math_random_multivariate_normal');
  771:   $safehole->wrap(\&Math::Random::random_multinomial,$safeeval,'&math_random_multinomial');
  772:   $safehole->wrap(\&Math::Random::random_noncentral_chi_square,$safeeval,'&math_random_noncentral_chi_square');
  773:   $safehole->wrap(\&Math::Random::random_noncentral_f,$safeeval,'&math_random_noncentral_f');
  774:   $safehole->wrap(\&Math::Random::random_normal,$safeeval,'&math_random_normal');
  775:   $safehole->wrap(\&Math::Random::random_permutation,$safeeval,'&math_random_permutation');
  776:   $safehole->wrap(\&Math::Random::random_permuted_index,$safeeval,'&math_random_permuted_index');
  777:   $safehole->wrap(\&Math::Random::random_uniform,$safeeval,'&math_random_uniform');
  778:   $safehole->wrap(\&Math::Random::random_poisson,$safeeval,'&math_random_poisson');
  779:   $safehole->wrap(\&Math::Random::random_uniform_integer,$safeeval,'&math_random_uniform_integer');
  780:   $safehole->wrap(\&Math::Random::random_negative_binomial,$safeeval,'&math_random_negative_binomial');
  781:   $safehole->wrap(\&Math::Random::random_binomial,$safeeval,'&math_random_binomial');
  782:   $safehole->wrap(\&Math::Random::random_seed_from_phrase,$safeeval,'&random_seed_from_phrase');
  783:   $safehole->wrap(\&Math::Random::random_set_seed_from_phrase,$safeeval,'&random_set_seed_from_phrase');
  784:   $safehole->wrap(\&Math::Random::random_get_seed,$safeeval,'&random_get_seed');
  785:   $safehole->wrap(\&Math::Random::random_set_seed,$safeeval,'&random_set_seed');
  786:   $safehole->wrap(\&Apache::lonxml::error,$safeeval,'&LONCAPA_INTERNAL_ERROR');
  787:   $safehole->wrap(\&Apache::lonxml::debug,$safeeval,'&LONCAPA_INTERNAL_DEBUG');
  788:   $safehole->wrap(\&Apache::caparesponse::get_sigrange,$safeeval,'&LONCAPA_INTERNAL_get_sigrange');
  789: 
  790: #need to inspect this class of ops
  791: # $safeeval->deny(":base_orig");
  792:   $safeeval->permit("require");
  793:   $safeinit .= ';$external::target="'.$target.'";';
  794:   &Apache::run::run($safeinit,$safeeval);
  795:   &initialize_rndseed($safeeval);
  796: }
  797: 
  798: sub initialize_rndseed {
  799:     my ($safeeval)=@_;
  800:     my $rndseed;
  801:     my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
  802:     $rndseed=&Apache::lonnet::rndseed($symb,$courseid,$domain,$name);
  803:     my $safeinit = '$external::randomseed="'.$rndseed.'";';
  804:     &Apache::lonxml::debug("Setting rndseed to $rndseed");
  805:     &Apache::run::run($safeinit,$safeeval);
  806: }
  807: 
  808: sub default_homework_load {
  809:     my ($safeeval)=@_;
  810:     &Apache::lonxml::debug('Loading default_homework');
  811:     my $default=&Apache::lonnet::getfile('/home/httpd/html/res/adm/includes/default_homework.lcpm');
  812:     if ($default eq -1) {
  813: 	&Apache::lonxml::error("<b>Unable to find <i>default_homework.lcpm</i></b>");
  814:     } else {
  815: 	&Apache::run::run($default,$safeeval);
  816: 	$Apache::lonxml::default_homework_loaded=1;
  817:     }
  818: }
  819: 
  820: {
  821:     my $alarm_depth;
  822:     sub init_alarm {
  823: 	alarm(0);
  824: 	$alarm_depth=0;
  825:     }
  826: 
  827:     sub start_alarm {
  828: 	if ($alarm_depth<1) {
  829: 	    my $old=alarm($Apache::lonnet::perlvar{'lonScriptTimeout'});
  830: 	    if ($old) {
  831: 		&Apache::lonxml::error("Cancelled an alarm of $old, this shouldn't occur.");
  832: 	    }
  833: 	}
  834: 	$alarm_depth++;
  835:     }
  836: 
  837:     sub end_alarm {
  838: 	$alarm_depth--;
  839: 	if ($alarm_depth<1) { alarm(0); }
  840:     }
  841: }
  842: my $metamode_was;
  843: sub startredirection {
  844:     if (!$Apache::lonxml::redirection) {
  845: 	$metamode_was=$Apache::lonxml::metamode;
  846:     }
  847:     $Apache::lonxml::metamode=0;
  848:     $Apache::lonxml::redirection++;
  849:     push (@Apache::lonxml::outputstack, '');
  850: }
  851: 
  852: sub endredirection {
  853:     if (!$Apache::lonxml::redirection) {
  854: 	&Apache::lonxml::error("Endredirection was called before a startredirection, perhaps you have unbalanced tags. Some debugging information:".join ":",caller);
  855: 	return '';
  856:     }
  857:     $Apache::lonxml::redirection--;
  858:     if (!$Apache::lonxml::redirection) {
  859: 	$Apache::lonxml::metamode=$metamode_was;
  860:     }
  861:     pop @Apache::lonxml::outputstack;
  862: }
  863: 
  864: sub end_tag {
  865:   my ($tagstack,$parstack,$token)=@_;
  866:   pop(@$tagstack);
  867:   pop(@$parstack);
  868:   &decreasedepth($token);
  869: }
  870: 
  871: sub initdepth {
  872:   @Apache::lonxml::depthcounter=();
  873:   $Apache::lonxml::depth=-1;
  874:   $Apache::lonxml::olddepth=-1;
  875: }
  876: 
  877: my @timers;
  878: my $lasttime;
  879: sub increasedepth {
  880:   my ($token) = @_;
  881:   $Apache::lonxml::depth++;
  882:   $Apache::lonxml::depthcounter[$Apache::lonxml::depth]++;
  883:   if ($Apache::lonxml::depthcounter[$Apache::lonxml::depth]==1) {
  884:     $Apache::lonxml::olddepth=$Apache::lonxml::depth;
  885:   }
  886:   my $time;
  887:   if ($Apache::lonxml::debug eq "1") {
  888:       push(@timers,[&gettimeofday()]);
  889:       $time=&tv_interval($lasttime);
  890:       $lasttime=[&gettimeofday()];
  891:   }
  892:   my $spacing='  'x($Apache::lonxml::depth-1);
  893:   my $curdepth=join('_',@Apache::lonxml::depthcounter);
  894:   &Apache::lonxml::debug("s$spacing$Apache::lonxml::depth : $Apache::lonxml::olddepth : $curdepth : $token->[1] : $time : \n");
  895: #print "<br />s $Apache::lonxml::depth : $Apache::lonxml::olddepth : $curdepth : $token->[1]\n";
  896: }
  897: 
  898: sub decreasedepth {
  899:   my ($token) = @_;
  900:   $Apache::lonxml::depth--;
  901:   if ($Apache::lonxml::depth<$Apache::lonxml::olddepth-1) {
  902:     $#Apache::lonxml::depthcounter--;
  903:     $Apache::lonxml::olddepth=$Apache::lonxml::depth+1;
  904:   }
  905:   if (  $Apache::lonxml::depth < -1) {
  906:     &Apache::lonxml::warning(&mt("Missing tags, unable to properly run file."));
  907:     $Apache::lonxml::depth='-1';
  908:   }
  909:   my ($timer,$time);
  910:   if ($Apache::lonxml::debug eq "1") {
  911:       $timer=pop(@timers);
  912:       $time=&tv_interval($lasttime);
  913:       $lasttime=[&gettimeofday()];
  914:   }
  915:   my $spacing='  'x$Apache::lonxml::depth;
  916:   my $curdepth=join('_',@Apache::lonxml::depthcounter);
  917:   &Apache::lonxml::debug("e$spacing$Apache::lonxml::depth : $Apache::lonxml::olddepth : $curdepth : $token->[1] : $time : ".&tv_interval($timer)."\n");
  918: #print "<br />e $Apache::lonxml::depth : $Apache::lonxml::olddepth : $token->[1] : $curdepth\n";
  919: }
  920: 
  921: sub get_all_text_unbalanced {
  922: #there is a copy of this in lonpublisher.pm
  923:     my($tag,$pars)= @_;
  924:     my $token;
  925:     my $result='';
  926:     $tag='<'.$tag.'>';
  927:     while ($token = $$pars[-1]->get_token) {
  928: 	if (($token->[0] eq 'T')||($token->[0] eq 'C')||($token->[0] eq 'D')) {
  929: 	    if ($token->[0] eq 'T' && $token->[2]) {
  930: 		$result.='<![CDATA['.$token->[1].']]>';
  931: 	    } else {
  932: 		$result.=$token->[1];
  933: 	    }
  934: 	} elsif ($token->[0] eq 'PI') {
  935: 	    $result.=$token->[2];
  936: 	} elsif ($token->[0] eq 'S') {
  937: 	    $result.=$token->[4];
  938: 	} elsif ($token->[0] eq 'E')  {
  939: 	    $result.=$token->[2];
  940: 	}
  941: 	if ($result =~ /\Q$tag\E/is) {
  942: 	    ($result,my $redo)=$result =~ /(.*)\Q$tag\E(.*)/is;
  943: 	    #&Apache::lonxml::debug('Got a winner with leftovers ::'.$2);
  944: 	    #&Apache::lonxml::debug('Result is :'.$1);
  945: 	    $redo=$tag.$redo;
  946: 	    &Apache::lonxml::newparser($pars,\$redo);
  947: 	    last;
  948: 	}
  949:     }
  950:     return $result
  951: }
  952: 
  953: sub increment_counter {
  954:     my ($increment) = @_;
  955:     if (defined($increment) && $increment gt 0) {
  956: 	$Apache::lonxml::counter+=$increment;
  957:     } else {
  958: 	$Apache::lonxml::counter++;
  959:     }
  960:     $Apache::lonxml::counter_changed=1;
  961: }
  962: 
  963: sub init_counter {
  964:     if ($env{'request.state'} eq 'construct') {
  965: 	$Apache::lonxml::counter=1;
  966: 	$Apache::lonxml::counter_changed=1;
  967:     } elsif (defined($env{'form.counter'})) {
  968: 	$Apache::lonxml::counter=$env{'form.counter'};
  969: 	$Apache::lonxml::counter_changed=0;
  970:     } else {
  971: 	$Apache::lonxml::counter=1;
  972: 	$Apache::lonxml::counter_changed=1;
  973:     }
  974: }
  975: 
  976: sub store_counter {
  977:     &Apache::lonnet::appenv(('form.counter' => $Apache::lonxml::counter));
  978:     return '';
  979: }
  980: 
  981: sub get_all_text {
  982:     my($tag,$pars,$style)= @_;
  983:     my $gotfullstack=1;
  984:     if (ref($pars) ne 'ARRAY') {
  985: 	$gotfullstack=0;
  986: 	$pars=[$pars];
  987:     }
  988:     if (ref($style) ne 'HASH') {
  989: 	$style={};
  990:     }
  991:     my $depth=0;
  992:     my $token;
  993:     my $result='';
  994:     if ( $tag =~ m:^/: ) { 
  995: 	my $tag=substr($tag,1); 
  996: 	#&Apache::lonxml::debug("have:$tag:");
  997: 	my $top_empty=0;
  998: 	while (($depth >=0) && ($#$pars > -1) && (!$top_empty)) {
  999: 	    while (($depth >=0) && ($token = $$pars[-1]->get_token)) {
 1000: 		#&Apache::lonxml::debug("e token:$token->[0]:$depth:$token->[1]:".$#$pars.":".$#Apache::lonxml::pwd);
 1001: 		if (($token->[0] eq 'T')||($token->[0] eq 'C')||($token->[0] eq 'D')) {
 1002: 		    if ($token->[2]) {
 1003: 			$result.='<![CDATA['.$token->[1].']]>';
 1004: 		    } else {
 1005: 			$result.=$token->[1];
 1006: 		    }
 1007: 		} elsif ($token->[0] eq 'PI') {
 1008: 		    $result.=$token->[2];
 1009: 		} elsif ($token->[0] eq 'S') {
 1010: 		    if ($token->[1] =~ /^\Q$tag\E$/i) { $depth++; }
 1011: 		    if ($token->[1] =~ /^LONCAPA_INTERNAL_TURN_STYLE_ON$/) { $Apache::lonxml::usestyle=1; }
 1012: 		    if ($token->[1] =~ /^LONCAPA_INTERNAL_TURN_STYLE_OFF$/) { $Apache::lonxml::usestyle=0; }
 1013: 		    $result.=$token->[4];
 1014: 		} elsif ($token->[0] eq 'E')  {
 1015: 		    if ( $token->[1] =~ /^\Q$tag\E$/i) { $depth--; }
 1016: 		    #skip sending back the last end tag
 1017: 		    if ($depth == 0 && exists($$style{'/'.$token->[1]}) && $Apache::lonxml::usestyle) {
 1018: 			my $string=
 1019: 			    '<LONCAPA_INTERNAL_TURN_STYLE_OFF end="yes" />'.
 1020: 				$$style{'/'.$token->[1]}.
 1021: 				    $token->[2].
 1022: 					'<LONCAPA_INTERNAL_TURN_STYLE_ON />';
 1023: 			&Apache::lonxml::newparser($pars,\$string);
 1024: 			#&Apache::lonxml::debug("reParsing $string");
 1025: 			next;
 1026: 		    }
 1027: 		    if ($depth > -1) {
 1028: 			$result.=$token->[2];
 1029: 		    } else {
 1030: 			$$pars[-1]->unget_token($token);
 1031: 		    }
 1032: 		}
 1033: 	    }
 1034: 	    if (($depth >=0) && ($#$pars == 0) ) { $top_empty=1; }
 1035: 	    if (($depth >=0) && ($#$pars > 0) ) {
 1036: 		pop(@$pars);
 1037: 		pop(@Apache::lonxml::pwd);
 1038: 	    }
 1039: 	}
 1040: 	if ($top_empty && $depth >= 0) {
 1041: 	    #never found the end tag ran out of text, throw error send back blank
 1042: 	    &error('Never found end tag for &lt;'.$tag.
 1043: 		   '&gt; current string <pre>'.
 1044: 		   &HTML::Entities::encode($result,'<>&"').
 1045: 		   '</pre>');
 1046: 	    if ($gotfullstack) {
 1047: 		my $newstring='</'.$tag.'>'.$result;
 1048: 		&Apache::lonxml::newparser($pars,\$newstring);
 1049: 	    }
 1050: 	    $result='';
 1051: 	}
 1052:     } else {
 1053: 	while ($#$pars > -1) {
 1054: 	    while ($token = $$pars[-1]->get_token) {
 1055: 		#&Apache::lonxml::debug("s token:$token->[0]:$depth:$token->[1]");
 1056: 		if (($token->[0] eq 'T')||($token->[0] eq 'C')||
 1057: 		    ($token->[0] eq 'D')) {
 1058: 		    if ($token->[2]) {
 1059: 			$result.='<![CDATA['.$token->[1].']]>';
 1060: 		    } else {
 1061: 			$result.=$token->[1];
 1062: 		    }
 1063: 		} elsif ($token->[0] eq 'PI') {
 1064: 		    $result.=$token->[2];
 1065: 		} elsif ($token->[0] eq 'S') {
 1066: 		    if ( $token->[1] =~ /^\Q$tag\E$/i) {
 1067: 			$$pars[-1]->unget_token($token); last;
 1068: 		    } else {
 1069: 			$result.=$token->[4];
 1070: 		    }
 1071: 		    if ($token->[1] =~ /^LONCAPA_INTERNAL_TURN_STYLE_ON$/) { $Apache::lonxml::usestyle=1; }
 1072: 		    if ($token->[1] =~ /^LONCAPA_INTERNAL_TURN_STYLE_OFF$/) { $Apache::lonxml::usestyle=0; }
 1073: 		} elsif ($token->[0] eq 'E')  {
 1074: 		    $result.=$token->[2];
 1075: 		}
 1076: 	    }
 1077: 	    if (($#$pars > 0) ) {
 1078: 		pop(@$pars);
 1079: 		pop(@Apache::lonxml::pwd);
 1080: 	    } else { last; }
 1081: 	}
 1082:     }
 1083:     #&Apache::lonxml::debug("Exit:$result:");
 1084:     return $result
 1085: }
 1086: 
 1087: sub newparser {
 1088:   my ($parser,$contentref,$dir) = @_;
 1089:   push (@$parser,HTML::LCParser->new($contentref));
 1090:   $$parser[-1]->xml_mode(1);
 1091:   $$parser[-1]->marked_sections(1);
 1092:   if ( $dir eq '' ) {
 1093:     push (@Apache::lonxml::pwd, $Apache::lonxml::pwd[$#Apache::lonxml::pwd]);
 1094:   } else {
 1095:     push (@Apache::lonxml::pwd, $dir);
 1096:   } 
 1097: }
 1098: 
 1099: sub parstring {
 1100:   my ($token) = @_;
 1101:   my $temp='';
 1102:   foreach (@{$token->[3]}) {
 1103:     unless ($_=~/\W/) {
 1104:       my $val=$token->[2]->{$_};
 1105:       $val =~ s/([\%\@\\\"\'])/\\$1/g;
 1106:       $val =~ s/(\$[^{a-zA-Z_])/\\$1/g;
 1107:       $val =~ s/(\$)$/\\$1/;
 1108:       #if ($val =~ m/^[\%\@]/) { $val="\\".$val; }
 1109:       $temp .= "my \$$_=\"$val\";";
 1110:     }
 1111:   }
 1112:   return $temp;
 1113: }
 1114: 
 1115: sub extlink {
 1116:     my ($res,$exact)=@_;
 1117:     if (!$exact) {
 1118: 	$res=&Apache::lonnet::hreflocation($Apache::lonxml::pwd[-1],$res);
 1119:     }
 1120:     push(@Apache::lonxml::extlinks,$res)	 
 1121: }
 1122: 
 1123: sub writeallows {
 1124:     unless ($#extlinks>=0) { return; }
 1125:     my $thisurl = &Apache::lonnet::clutter(shift);
 1126:     if ($env{'httpref.'.$thisurl}) {
 1127: 	$thisurl=$env{'httpref.'.$thisurl};
 1128:     }
 1129:     my $thisdir=$thisurl;
 1130:     $thisdir=~s/\/[^\/]+$//;
 1131:     my %httpref=();
 1132:     foreach (@extlinks) {
 1133:        $httpref{'httpref.'.
 1134:  	        &Apache::lonnet::hreflocation($thisdir,$_)}=$thisurl;
 1135:     }
 1136:     @extlinks=();
 1137:     &Apache::lonnet::appenv(%httpref);
 1138: }
 1139: 
 1140: sub register_ssi {
 1141:     my ($url,%form)=@_;
 1142:     push (@Apache::lonxml::ssi_info,{'url'=>$url,'form'=>\%form});
 1143:     return '';
 1144: }
 1145: 
 1146: sub do_registered_ssi {
 1147:     foreach my $info (@Apache::lonxml::ssi_info) {
 1148: 	my %form=%{ $info->{'form'}};
 1149: 	my $url=$info->{'url'};
 1150: 	&Apache::lonnet::ssi($url,%form);
 1151:     }
 1152: }
 1153: #
 1154: # Afterburner handles anchors, highlights and links
 1155: #
 1156: sub afterburn {
 1157:     my $result=shift;
 1158:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 1159: 					    ['highlight','anchor','link']);
 1160:     if ($env{'form.highlight'}) {
 1161:        foreach (split(/\,/,$env{'form.highlight'})) {
 1162:            my $anchorname=$_;
 1163: 	   my $matchthis=$anchorname;
 1164:            $matchthis=~s/\_+/\\s\+/g;
 1165:            $result=~s/(\Q$matchthis\E)/\<font color=\"red\"\>$1\<\/font\>/gs;
 1166:        }
 1167:     }
 1168:     if ($env{'form.link'}) {
 1169:        foreach (split(/\,/,$env{'form.link'})) {
 1170:            my ($anchorname,$linkurl)=split(/\>/,$_);
 1171: 	   my $matchthis=$anchorname;
 1172:            $matchthis=~s/\_+/\\s\+/g;
 1173:            $result=~s/(\Q$matchthis\E)/\<a href=\"$linkurl\"\>$1\<\/a\>/gs;
 1174:        }
 1175:     }
 1176:     if ($env{'form.anchor'}) {
 1177:         my $anchorname=$env{'form.anchor'};
 1178: 	my $matchthis=$anchorname;
 1179:         $matchthis=~s/\_+/\\s\+/g;
 1180:         $result=~s/(\Q$matchthis\E)/\<a name=\"$anchorname\"\>$1\<\/a\>/s;
 1181:         $result.=(<<"ENDSCRIPT");
 1182: <script type="text/javascript">
 1183:     document.location.hash='$anchorname';
 1184: </script>
 1185: ENDSCRIPT
 1186:     }
 1187:     return $result;
 1188: }
 1189: 
 1190: sub storefile {
 1191:     my ($file,$contents)=@_;
 1192:     &Apache::lonnet::correct_line_ends(\$contents);
 1193:     if (my $fh=Apache::File->new('>'.$file)) {
 1194: 	print $fh $contents;
 1195:         $fh->close();
 1196:         return 1;
 1197:     } else {
 1198: 	&warning("Unable to save file $file");
 1199: 	return 0;
 1200:     }
 1201: }
 1202: 
 1203: sub createnewhtml {
 1204:     my $title=&mt('Title of document goes here');
 1205:     my $body=&mt('Body of document goes here');
 1206:     my $filecontents=(<<SIMPLECONTENT);
 1207: <html>
 1208: <head>
 1209: <title>$title</title>
 1210: </head>
 1211: <body bgcolor="#FFFFFF">
 1212: $body
 1213: </body>
 1214: </html>
 1215: SIMPLECONTENT
 1216:     return $filecontents;
 1217: }
 1218: 
 1219: sub createnewsty {
 1220:   my $filecontents=(<<SIMPLECONTENT);
 1221: <definetag name="">
 1222:     <render>
 1223:        <web></web>
 1224:        <tex></tex>
 1225:     </render>
 1226: </definetag>
 1227: SIMPLECONTENT
 1228:   return $filecontents;
 1229: }
 1230: 
 1231: 
 1232: sub inserteditinfo {
 1233:       my ($result,$filecontents,$filetype)=@_;
 1234:       $filecontents = &HTML::Entities::encode($filecontents,'<>&"');
 1235: #      my $editheader='<a href="#editsection">Edit below</a><hr />';
 1236:       my $xml_help = '';
 1237:       my $initialize='';
 1238:       if ($filetype eq 'html') {
 1239: 	  my $addbuttons=&Apache::lonhtmlcommon::htmlareaaddbuttons();
 1240: 	  $initialize=&Apache::lonhtmlcommon::htmlareaheaders().
 1241: 	      &Apache::lonhtmlcommon::spellheader();
 1242: 	  if (!&Apache::lonhtmlcommon::htmlareablocked() &&
 1243: 	      &Apache::lonhtmlcommon::htmlareabrowser()) {
 1244: 	      $initialize.=(<<FULLPAGE);
 1245: <script type="text/javascript">
 1246: $addbuttons
 1247: 
 1248:     HTMLArea.loadPlugin("FullPage");
 1249: 
 1250:     function initDocument() {
 1251: 	var editor=new HTMLArea("filecont",config);
 1252: 	editor.registerPlugin(FullPage);
 1253: 	editor.generate();
 1254:     }
 1255: </script>
 1256: FULLPAGE
 1257:           } else {
 1258: 	      $initialize.=(<<FULLPAGE);
 1259: <script type="text/javascript">
 1260: $addbuttons
 1261:     function initDocument() {
 1262:     }
 1263: </script>
 1264: FULLPAGE
 1265: 	  }
 1266:           $result=~s/\<body([^\>]*)\>/\<body onload="initDocument()" $1\>/i;
 1267: 	  $xml_help=&Apache::loncommon::helpLatexCheatsheet();
 1268:       }
 1269:       my $cleanbut = '';
 1270: 
 1271:       my $titledisplay=&display_title();
 1272:       my %lt=&Apache::lonlocal::texthash('st' => 'Save this',
 1273: 					 'vi' => 'View',
 1274: 					 'ed' => 'Edit');
 1275:       my $buttons=(<<BUTTONS);
 1276: $cleanbut
 1277: <input type="submit" name="savethisfile" accesskey="s"  value="$lt{'st'}" />
 1278: <input type="submit" name="viewmode" accesskey="v" value="$lt{'vi'}" />
 1279: BUTTONS
 1280:       $buttons.=&Apache::lonhtmlcommon::spelllink('xmledit','filecont');
 1281:       $buttons.=&Apache::lonhtmlcommon::htmlareaselectactive('filecont');
 1282:       my $editfooter=(<<ENDFOOTER);
 1283: $initialize
 1284: <hr />
 1285: <a name="editsection" />
 1286: <form method="post" name="xmledit">
 1287: $xml_help
 1288: <input type="hidden" name="editmode" value="$lt{'ed'}" />
 1289: $buttons<br />
 1290: <textarea style="width:100%" cols="80" rows="44" name="filecont" id="filecont">$filecontents</textarea>
 1291: <br />$buttons
 1292: <br />
 1293: </form>
 1294: $titledisplay
 1295: </body>
 1296: ENDFOOTER
 1297: #      $result=~s/(\<body[^\>]*\>)/$1$editheader/is;
 1298:       $result=~s/(\<\/body\>)/$editfooter/is;
 1299:       return $result;
 1300: }
 1301: 
 1302: sub get_target {
 1303:   my $viewgrades=&Apache::lonnet::allowed('vgr',$env{'request.course.id'});
 1304:   if ( $env{'request.state'} eq 'published') {
 1305:     if ( defined($env{'form.grade_target'})
 1306: 	 && ($viewgrades == 'F' )) {
 1307:       return ($env{'form.grade_target'});
 1308:     } elsif (defined($env{'form.grade_target'})) {
 1309:       if (($env{'form.grade_target'} eq 'web') ||
 1310: 	  ($env{'form.grade_target'} eq 'tex') ) {
 1311: 	return $env{'form.grade_target'}
 1312:       } else {
 1313: 	return 'web';
 1314:       }
 1315:     } else {
 1316:       return 'web';
 1317:     }
 1318:   } elsif ($env{'request.state'} eq 'construct') {
 1319:     if ( defined($env{'form.grade_target'})) {
 1320:       return ($env{'form.grade_target'});
 1321:     } else {
 1322:       return 'web';
 1323:     }
 1324:   } else {
 1325:     return 'web';
 1326:   }
 1327: }
 1328: 
 1329: sub handler {
 1330:     my $request=shift;
 1331:     
 1332:     my $target=&get_target();
 1333:     
 1334:     $Apache::lonxml::debug=$env{'user.debug'};
 1335:     
 1336:     &Apache::loncommon::content_type($request,'text/html');
 1337:     &Apache::loncommon::no_cache($request);
 1338:     if ($env{'request.state'} eq 'published') {
 1339: 	$request->set_last_modified(&Apache::lonnet::metadata($request->uri,
 1340: 							      'lastrevisiondate'));
 1341:     }
 1342:     $request->send_http_header;
 1343:     
 1344:     return OK if $request->header_only;
 1345: 
 1346: 
 1347:     my $file=&Apache::lonnet::filelocation("",$request->uri);
 1348:     my $filetype;
 1349:     if ($file =~ /\.sty$/) {
 1350: 	$filetype='sty';
 1351:     } else {
 1352: 	$filetype='html';
 1353:     }
 1354: #
 1355: # Edit action? Save file.
 1356: #
 1357:     unless ($env{'request.state'} eq 'published') {
 1358: 	if ($env{'form.savethisfile'}) {
 1359: 	    if (&storefile($file,$env{'form.filecont'})) {
 1360: 		&Apache::lonxml::info("<font COLOR=\"#0000FF\">".
 1361: 				      &mt('Updated').": ".
 1362: 				      &Apache::lonlocal::locallocaltime(time).
 1363: 				      " </font>");
 1364: 	    } 
 1365: 	}
 1366:     }
 1367:     my %mystyle;
 1368:     my $result = '';
 1369:     my $filecontents=&Apache::lonnet::getfile($file);
 1370:     if ($filecontents eq -1) {
 1371: 	my $bodytag=&Apache::loncommon::bodytag('File Error');
 1372: 	my $fnf=&mt('File not found');
 1373: 	$result=(<<ENDNOTFOUND);
 1374: <html>
 1375: <head>
 1376: <title>$fnf</title>
 1377: </head>
 1378: $bodytag
 1379: <b>$fnf: $file</b>
 1380: </body>
 1381: </html>
 1382: ENDNOTFOUND
 1383:         $filecontents='';
 1384: 	if ($env{'request.state'} ne 'published') {
 1385: 	    if ($filetype eq 'sty') {
 1386: 		$filecontents=&createnewsty();
 1387: 	    } else {
 1388: 		$filecontents=&createnewhtml();
 1389: 	    }
 1390: 	    $env{'form.editmode'}='Edit'; #force edit mode
 1391: 	}
 1392:     } else {
 1393: 	unless ($env{'request.state'} eq 'published') {
 1394: 	    if ($filecontents=~/BEGIN LON-CAPA Internal/) {
 1395: 		&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.'));
 1396: 	    }
 1397: #
 1398: # we are in construction space, see if edit mode forced
 1399:             &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 1400: 						    ['editmode']);
 1401: 	}
 1402: 	if (!$env{'form.editmode'} || $env{'form.viewmode'}) {
 1403: 	    $result = &Apache::lonxml::xmlparse($request,$target,$filecontents,
 1404: 						'',%mystyle);
 1405: 	    undef($Apache::lonhomework::parsing_a_task);
 1406: 	    &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 1407: 						    ['rawmode']);
 1408: 	    if ($env{'rawmode'}) { $result = $filecontents; }
 1409: 	}
 1410:     }
 1411:     
 1412: #
 1413: # Edit action? Insert editing commands
 1414: #
 1415:     unless ($env{'request.state'} eq 'published') {
 1416: 	if ($env{'form.editmode'} && (!($env{'form.viewmode'}))) {
 1417: 	    my $displayfile=$request->uri;
 1418: 	    $displayfile=~s/^\/[^\/]*//;
 1419: 	    my $bodytag='<body bgcolor="#FFFFFF">';
 1420: 	    if ($env{'environment.remote'} eq 'off') {
 1421: 		$bodytag=&Apache::loncommon::bodytag();
 1422: 	    }
 1423: 	    $result='<html>'.$bodytag.
 1424: 		&Apache::lonxml::message_location().'<h3>'.
 1425: 		$displayfile.
 1426: 		'</h3></body></html>';
 1427: 	    $result=&inserteditinfo($result,$filecontents,$filetype);
 1428: 	}
 1429:     }
 1430:     if ($filetype eq 'html') { writeallows($request->uri); }
 1431: 	
 1432:     
 1433:     &Apache::lonxml::add_messages(\$result);
 1434:     $request->print($result);
 1435:     
 1436:     return OK;
 1437: }
 1438: 
 1439: sub display_title {
 1440:     my $result;
 1441:     if ($env{'request.state'} eq 'construct') {
 1442: 	my $title=&Apache::lonnet::gettitle();
 1443: 	if (!defined($title) || $title eq '') {
 1444: 	    $title = $env{'request.filename'};
 1445: 	    $title = substr($title, rindex($title, '/') + 1);
 1446: 	}
 1447: 	$result = "<script type='text/javascript'>top.document.title = '$title - LON-CAPA Construction Space';</script>";
 1448:     }
 1449:     return $result;
 1450: }
 1451: 
 1452: sub debug {
 1453:     if ($Apache::lonxml::debug eq "1") {
 1454: 	$|=1;
 1455: 	my $request=$Apache::lonxml::request;
 1456: 	if (!$request) {
 1457: 	    eval { $request=Apache->request; };
 1458: 	}
 1459: 	if (!$request) {
 1460: 	    eval { $request=Apache2::RequestUtil->request; };
 1461: 	}
 1462: 	$request->print('<font size="-2"><pre>DEBUG:'.&HTML::Entities::encode($_[0],'<>&"')."</pre></font>\n");
 1463: 	#&Apache::lonnet::logthis($_[0]);
 1464:     }
 1465: }
 1466: 
 1467: sub show_error_warn_msg {
 1468:     if ($env{'request.filename'} eq '/home/httpd/html/res/lib/templates/simpleproblem.problem' &&
 1469: 	&Apache::lonnet::allowed('mdc',$env{'request.course.id'})) {
 1470: 	return 1;
 1471:     }
 1472:     return (($Apache::lonxml::debug eq 1) ||
 1473: 	    ($env{'request.state'} eq 'construct') ||
 1474: 	    ($Apache::lonhomework::browse eq 'F'
 1475: 	     &&
 1476: 	     $env{'form.show_errors'} eq 'on'));
 1477: }
 1478: 
 1479: sub error {
 1480:     $errorcount++;
 1481:     if ( &show_error_warn_msg() ) {
 1482: 	# If printing in construction space, put the error inside <pre></pre>
 1483: 	push(@Apache::lonxml::error_messages,
 1484: 	     $Apache::lonxml::warnings_error_header.
 1485: 	     "<b>ERROR:</b>".join("<br />\n",@_)."<br />\n");
 1486: 	$Apache::lonxml::warnings_error_header='';
 1487:     } else {
 1488: 	my $errormsg;
 1489: 	my ($symb)=&Apache::lonnet::symbread();
 1490: 	if ( !$symb ) {
 1491: 	    #public or browsers
 1492: 	    $errormsg=&mt("An error occured while processing this resource. The author has been notified.");
 1493: 	} 
 1494: 	#notify author
 1495: 	&Apache::lonmsg::author_res_msg($env{'request.filename'},join('<br />',@_));
 1496: 	#notify course
 1497: 	if ( $symb && $env{'request.course.id'} ) {
 1498: 	    my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 1499: 	    my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1500: 	    my (undef,%users)=&Apache::lonfeedback::decide_receiver(undef,0,1,1,1);
 1501: 	    my $declutter=&Apache::lonnet::declutter($env{'request.filename'});
 1502: 	    my @userlist;
 1503: 	    foreach (keys %users) {
 1504: 		my ($user,$domain) = split(/:/, $_);
 1505: 		push(@userlist,"$user\@$domain");
 1506: 		my $key=$declutter.'_'.$user.'_'.$domain;
 1507: 		my %lastnotified=&Apache::lonnet::get('nohist_xmlerrornotifications',
 1508: 						      [$key],
 1509: 						      $cdom,$cnum);
 1510: 		my $now=time;
 1511: 		if ($now-$lastnotified{$key}>86400) {
 1512: 		    &Apache::lonmsg::user_normal_msg($user,$domain,
 1513: 						 "Error [$declutter]",join('<br />',@_));
 1514: 		    &Apache::lonnet::put('nohist_xmlerrornotifications',
 1515: 					 {$key => $now},
 1516: 					 $cdom,$cnum);		
 1517: 		}
 1518: 	    }
 1519: 	    if ($env{'request.role.adv'}) {
 1520: 		$errormsg=&mt("An error occured while processing this resource. The course personnel ([_1]) and the author have been notified.",join(', ',@userlist));
 1521: 	    } else {
 1522: 		$errormsg=&mt("An error occured while processing this resource. The instructor has been notified.");
 1523: 	    }
 1524: 	}
 1525: 	push(@Apache::lonxml::error_messages,"<b>$errormsg</b> <br />");
 1526:     }
 1527: }
 1528: 
 1529: sub warning {
 1530:     $warningcount++;
 1531:   
 1532:     if ($env{'form.grade_target'} ne 'tex') {
 1533: 	if ( &show_error_warn_msg() ) {
 1534: 	    push(@Apache::lonxml::warning_messages,
 1535: 		 $Apache::lonxml::warnings_error_header.
 1536: 		 "<b>W</b>ARNING<b>:</b>".join('<br />',@_)."<br />\n");
 1537: 	    $Apache::lonxml::warnings_error_header='';
 1538: 	}
 1539:     }
 1540: }
 1541: 
 1542: sub info {
 1543:     if ($env{'form.grade_target'} ne 'tex' 
 1544: 	&& $env{'request.state'} eq 'construct') {
 1545: 	push(@Apache::lonxml::info_messages,join('<br />',@_)."<br />\n");
 1546:     }
 1547: }
 1548: 
 1549: sub message_location {
 1550:     return '__LONCAPA_INTERNAL_MESSAGE_LOCATION__';
 1551: }
 1552: 
 1553: sub add_messages {
 1554:     my ($msg)=@_;
 1555:     my $result=join(' ',
 1556: 		    @Apache::lonxml::info_messages,
 1557: 		    @Apache::lonxml::error_messages,
 1558: 		    @Apache::lonxml::warning_messages);
 1559:     undef(@Apache::lonxml::info_messages);
 1560:     undef(@Apache::lonxml::error_messages);
 1561:     undef(@Apache::lonxml::warning_messages);
 1562:     $$msg=~s/__LONCAPA_INTERNAL_MESSAGE_LOCATION__/$result/;
 1563:     $$msg=~s/__LONCAPA_INTERNAL_MESSAGE_LOCATION__//g;
 1564: }
 1565: 
 1566: sub get_param {
 1567:     my ($param,$parstack,$safeeval,$context,$case_insensitive) = @_;
 1568:     if ( ! $context ) { $context = -1; }
 1569:     my $args ='';
 1570:     if ( $#$parstack > (-2-$context) ) { $args=$$parstack[$context]; }
 1571:     if ( ! $Apache::lonxml::usestyle ) {
 1572: 	$args=$Apache::lonxml::style_values.$args;
 1573:     }
 1574:     if ( ! $args ) { return undef; }
 1575:     if ( $case_insensitive ) {
 1576: 	if ($args =~ s/(my \$)(\Q$param\E)(=\")/$1.lc($2).$3/ei) {
 1577: 	    return &Apache::run::run("{$args;".'return $'.$param.'}',
 1578:                                      $safeeval); #'
 1579: 	} else {
 1580: 	    return undef;
 1581: 	}
 1582:     } else {
 1583: 	if ( $args =~ /my \$\Q$param\E=\"/ ) {
 1584: 	    return &Apache::run::run("{$args;".'return $'.$param.'}',
 1585:                                      $safeeval); #'
 1586: 	} else {
 1587: 	    return undef;
 1588: 	}
 1589:     }
 1590: }
 1591: 
 1592: sub get_param_var {
 1593:   my ($param,$parstack,$safeeval,$context,$case_insensitive) = @_;
 1594:   if ( ! $context ) { $context = -1; }
 1595:   my $args ='';
 1596:   if ( $#$parstack > (-2-$context) ) { $args=$$parstack[$context]; }
 1597:   if ( ! $Apache::lonxml::usestyle ) {
 1598:       $args=$Apache::lonxml::style_values.$args;
 1599:   }
 1600:   &Apache::lonxml::debug("Args are $args param is $param");
 1601:   if ($case_insensitive) {
 1602:       if (! ($args=~s/(my \$)(\Q$param\E)(=\")/$1.lc($2).$3/ei)) {
 1603: 	  return undef;
 1604:       }
 1605:   } elsif ( $args !~ /my \$\Q$param\E=\"/ ) { return undef; }
 1606:   my $value=&Apache::run::run("{$args;".'return $'.$param.'}',$safeeval); #'
 1607:   &Apache::lonxml::debug("first run is $value");
 1608:   if ($value =~ /^[\$\@\%][a-zA-Z_]\w*$/) {
 1609:       &Apache::lonxml::debug("doing second");
 1610:       my @result=&Apache::run::run("return $value",$safeeval,1);
 1611:       if (!defined($result[0])) {
 1612: 	  return $value
 1613:       } else {
 1614: 	  if (wantarray) { return @result; } else { return $result[0]; }
 1615:       }
 1616:   } else {
 1617:     return $value;
 1618:   }
 1619: }
 1620: 
 1621: sub register_insert {
 1622:   my @data = split /\n/, &Apache::lonnet::getfile('/home/httpd/lonTabs/insertlist.tab');
 1623:   my $i;
 1624:   my $tagnum=0;
 1625:   my @order;
 1626:   for ($i=0;$i < $#data; $i++) {
 1627:     my $line = $data[$i];
 1628:     if ( $line =~ /^\#/ || $line =~ /^\s*\n/) { next; }
 1629:     if ( $line =~ /TABLE/ ) { last; }
 1630:     my ($tag,$descrip,$color,$function,$show,$helpfile,$helpdesc) = split(/,/, $line);
 1631:     if ($tag) {
 1632:       $insertlist{"$tagnum.tag"} = $tag;
 1633:       $insertlist{"$tagnum.description"} = $descrip;
 1634:       $insertlist{"$tagnum.color"} = $color;
 1635:       $insertlist{"$tagnum.function"} = $function;
 1636:       if (!defined($show)) { $show='yes'; }
 1637:       $insertlist{"$tagnum.show"}= $show;
 1638:       $insertlist{"$tagnum.helpfile"} = $helpfile;
 1639:       $insertlist{"$tagnum.helpdesc"} = $helpdesc;
 1640:       $insertlist{"$tag.num"}=$tagnum;
 1641:       $tagnum++;
 1642:     }
 1643:   }
 1644:   $i++; #skipping TABLE line
 1645:   $tagnum = 0;
 1646:   for (;$i < $#data;$i++) {
 1647:     my $line = $data[$i];
 1648:     my ($mnemonic,@which) = split(/ +/,$line);
 1649:     my $tag = $insertlist{"$tagnum.tag"};
 1650:     for (my $j=0;$j <=$#which;$j++) {
 1651:       if ( $which[$j] eq 'Y' ) {
 1652: 	if ($insertlist{"$j.show"} ne 'no') {
 1653: 	  push(@{ $insertlist{"$tag.which"} },$j);
 1654: 	}
 1655:       }
 1656:     }
 1657:     $tagnum++;
 1658:   }
 1659: }
 1660: 
 1661: sub description {
 1662:   my ($token)=@_;
 1663:   my $tagnum;
 1664:   my $tag=$token->[1];
 1665:   foreach my $namespace (reverse @Apache::lonxml::namespace) {
 1666:     my $testtag=$namespace.'::'.$tag;
 1667:     $tagnum=$insertlist{"$testtag.num"};
 1668:     if (defined($tagnum)) { last; }
 1669:   }
 1670:   if (!defined ($tagnum)) { $tagnum=$Apache::lonxml::insertlist{"$tag.num"}; }
 1671:   return $insertlist{$tagnum.'.description'};
 1672: }
 1673: 
 1674: # Returns a list containing the help file, and the description
 1675: sub helpinfo {
 1676:   my ($token)=@_;
 1677:   my $tagnum;
 1678:   my $tag=$token->[1];
 1679:   foreach my $namespace (reverse @Apache::lonxml::namespace) {
 1680:     my $testtag=$namespace.'::'.$tag;
 1681:     $tagnum=$insertlist{"$testtag.num"};
 1682:     if (defined($tagnum)) { last; }
 1683:   }
 1684:   if (!defined ($tagnum)) { $tagnum=$Apache::lonxml::insertlist{"$tag.num"}; }
 1685:   return ($insertlist{$tagnum.'.helpfile'}, $insertlist{$tagnum.'.helpdesc'});
 1686: }
 1687: 
 1688: # ----------------------------------------------------------------- whichuser
 1689: # returns a list of $symb, $courseid, $domain, $name that is correct for
 1690: # calls to lonnet functions for this setup.
 1691: # - looks for form.grade_ parameters
 1692: sub whichuser {
 1693:   my ($passedsymb)=@_;
 1694:   my ($symb,$courseid,$domain,$name,$publicuser);
 1695:   if (defined($env{'form.grade_symb'})) {
 1696:       my ($tmp_courseid)=
 1697: 	  &Apache::loncommon::get_env_multiple('form.grade_courseid');
 1698:       my $allowed=&Apache::lonnet::allowed('vgr',$tmp_courseid);
 1699:       if (!$allowed && 
 1700: 	  exists($env{'request.course.sec'}) && 
 1701: 	  $env{'request.course.sec'} !~ /^\s*$/) {
 1702: 	  $allowed=&Apache::lonnet::allowed('vgr',$tmp_courseid.
 1703: 					    '/'.$env{'request.course.sec'});
 1704:       }
 1705:       if ($allowed) {
 1706: 	  ($symb)=&Apache::loncommon::get_env_multiple('form.grade_symb');
 1707: 	  $courseid=$tmp_courseid;
 1708: 	  ($domain)=&Apache::loncommon::get_env_multiple('form.grade_domain');
 1709: 	  ($name)=&Apache::loncommon::get_env_multiple('form.grade_username');
 1710: 	  return ($symb,$courseid,$domain,$name,$publicuser);
 1711:       }
 1712:   }
 1713:   if (!$passedsymb) {
 1714:       $symb=&Apache::lonnet::symbread();
 1715:   } else {
 1716:       $symb=$passedsymb;
 1717:   }
 1718:   $courseid=$env{'request.course.id'};
 1719:   $domain=$env{'user.domain'};
 1720:   $name=$env{'user.name'};
 1721:   if ($name eq 'public' && $domain eq 'public') {
 1722:       if (!defined($env{'form.username'})) {
 1723: 	  $env{'form.username'}.=time.rand(10000000);
 1724:       }
 1725:       $name.=$env{'form.username'};
 1726:   }
 1727:   return ($symb,$courseid,$domain,$name,$publicuser);
 1728: }
 1729: 
 1730: 1;
 1731: __END__
 1732: 
 1733: 

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