File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.350: download - view: text, annotated - select for diffs
Thu Dec 9 23:45:59 2004 UTC (19 years, 5 months ago) by albertel
Branches: MAIN
CVS tags: version_1_3_1, version_1_3_0, version_1_2_99_1, HEAD
- BUG#3704, also whichuser will now will better if a user is trying to force through a course/symb/user/daom cahnge,

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

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